参考代码
const nextBtn = document.querySelector("#next");
const prevBtn = document.querySelector("#prev");
const i1 = document.querySelectorAll(".page1");
const i2 = document.querySelectorAll(".page2");
const p1 = document.querySelector(".page1.right");
const p2 = document.querySelector(".page2.left");
const imgs = [
"./img/a01.jpg",
"./img/a02.jpg",
"./img/a03.jpg",
"./img/a04.jpg",
"./img/a05.jpg",
];
const imgLen = imgs.length;
let curAction = "";
let curIndex = imgLen * 100000;
function setBG(url) {
return function (el) {
el.style.backgroundImage = `url(${url})`;
};
}
nextBtn.addEventListener("click", async () => {
p1.style.transform = "rotateY(0)";
p2.style.transform = "rotateY(180deg)";
if (!curAction || curAction === "prev") {
i1.forEach(setBG(imgs[curIndex % imgLen]));
i2.forEach(setBG(imgs[(curIndex + 1) % imgLen]));
}
curAction = "next";
const ani1 = p1.animate([{ transform: "rotateY(-180deg)" }], {
duration: 1000,
fill: "forwards",
});
const ani2 = p2.animate([{ transform: "rotateY(0)" }], {
duration: 1000,
fill: "forwards",
});
await Promise.all([ani1.finished, ani2.finished]);
ani1.cancel();
ani2.cancel();
curIndex++;
i1.forEach(setBG(imgs[curIndex % imgLen]));
i2.forEach(setBG(imgs[(curIndex + 1) % imgLen]));
});
prevBtn.addEventListener("click", async () => {
p1.style.transform = "rotateY(-180deg)";
p2.style.transform = "rotateY(0)";
if (!curAction || curAction === "next") {
i2.forEach(setBG(imgs[curIndex % imgLen]));
i1.forEach(setBG(imgs[(curIndex - 1) % imgLen]));
}
curAction = "prev";
const ani1 = p1.animate([{ transform: "rotateY(0deg)" }], {
duration: 1000,
fill: "forwards",
});
const ani2 = p2.animate([{ transform: "rotateY(180deg)" }], {
duration: 1000,
fill: "forwards",
});
await Promise.all([ani1.finished, ani2.finished]);
ani1.cancel();
ani2.cancel();
curIndex--;
i2.forEach(setBG(imgs[curIndex % imgLen]));
i1.forEach(setBG(imgs[(curIndex - 1) % imgLen]));
});
在线实例
demo