提问人:BedSon 提问时间:11/8/2023 更新时间:11/8/2023 访问量:30
简单的 img 图库交叉淡入淡出效果
Simple img gallery crossfading effect
问:
我正在学习一些javascript,并想制作一个在页面顶部带有图片库的网页。这是我到目前为止的结果:https://streamable.com/v636mv 我通过PHP从服务器加载图像,并使用javascript函数显示它们。
但看起来每隔一段时间就会发生一些 blib,我不知道如何解决它。 我希望 CSS 和 html 应该没问题,所以问题很可能出在 javascript 本身上? 我最终得到了 setInterval 函数,该函数以 5 秒的间隔调用我的 crossfadeFunction。
(我想做一些简单的东西,不使用任何库,只是因为我不理解它们,恐怕)。
无论如何,这里是代码的链接:https://pastebin.com/Bj1P2vuR
对于 JavaScript:
function preloadImages() {
for (let i = 0; i < imgNamesArray.length; i++) {
const image = new Image();
image.src = `./images/${imgNamesArray[i]}`;
image.onload = () => {
// You can optionally do something when each image is preloaded
};
}
}
fetch("gallery.php")
.then(Response => Response.json())
.then(fetchedData => {
// tuto nieco rob s imgNamesmi ?
imgNamesArray = fetchedData;
console.log(imgNamesArray);
//const currentImage = document.getElementById('currentImage');
//currentImage.src = `./images/${imgNamesArray[0]}`;
// displayNextImage();
preloadImages();
const initialIndex = Math.floor(Math.random() * imgNamesArray.length);
const initialImageSrc = `./images/${imgNamesArray[initialIndex]}`;
currentImage.src = initialImageSrc;
/* setInterval(() => {
// displayNextImage();
crossfade();
}, 5000); */
setInterval(crossfadeII, 5000);
})
.catch(error => console.error("Error: ", error));
function displayNextImage() {
currentIndex = (currentIndex + 1) % imgNamesArray.length;
console.log(currentIndex);
const currentImage = document.getElementById("currentImage");
currentImage.src = `./images/${imgNamesArray[currentIndex]}`;
}
function crossfadeII() {
let newIndex;
do {
newIndex = Math.floor(Math.random() * imgNamesArray.length);
} while (newIndex === previousIndex || newIndex === currentIndex);
previousIndex = currentIndex;
currentIndex = newIndex;
// Preload the next image
const preloadIndex = (currentIndex + 1) % imgNamesArray.length;
const preloadImage = new Image();
preloadImage.src = `./images/${imgNamesArray[preloadIndex]}`;
currentImage.src = `./images/${imgNamesArray[currentIndex]}`;
console.log(`previousIndex: ${previousIndex}, currentIndex: ${currentIndex}, newIndex: ${newIndex}, match: ${previousIndex === currentIndex ? "matched" : newIndex}`);
// currentIndex = (currentIndex + 1) % imgNamesArray.length;
if (currentImage.classList.contains("current")) {
currentImage.classList.remove("current");
currentImage.classList.add("next");
} else {
currentImage.classList.remove("next");
currentImage.classList.add("current");
}
if (nextImage.classList.contains("next")) {
nextImage.classList.remove("next");
nextImage.classList.add("current");
nextImage.src = `./images/${imgNamesArray[previousIndex]}`;
// preloadImages();
} else {
// console.log("lets imagine");
nextImage.classList.remove("current");
nextImage.classList.add("next");
}
}
非常感谢
答: 暂无答案
评论