使用 JS 和 JQuery 制作幻灯片延迟图像循环



我正在尝试使用JS和JQuery创建小幻灯片。下面的代码可以工作(有点(,但在显示下一个图像之前不会延迟;马上就展示出来。在显示下一张图片之前,我试图让它延迟5秒。我有点新手,所以如果代码不可靠,我很抱歉。

*URL已更改,使其更具可读性。

谢谢你的帮助!

var backgroundImg = ["https://x1.jpg", "https://x2.jpg"];
var backgroundImgLength = backgroundImg.length;
var z = 0;
do {
slideShow(backgroundImg[z]);
z++;
}
while (z < backgroundImgLength);
function slideShow(url) {
setTimeout(function() {

$('.header-section').css('background-image', 'url(' + url + ')');
}, 5000);        
}

我会尝试以这种方式使用它:

const backgroundImg = [
"https://picsum.photos/id/237/200/300",
"https://picsum.photos/id/239/200/300"
];
const backgroundImgLength = backgroundImg.length;
let backgroundImgIndex = 0;
let backgroundImgUrl = backgroundImg[backgroundImgIndex];
const changeImage = function() {
$('.header-section').css('background-image', 'url(' + backgroundImgUrl + ')');
}
const getNextImgIndex = function() {
return (backgroundImgIndex + 1 < backgroundImgLength) ? backgroundImgIndex + 1 : 0;
}
// setInterval allows us to run a function repeatedly,
// starting after the interval of time,
// then repeating continuously at that interval.
const timerId = setInterval(function() {
backgroundImgIndex = getNextImgIndex();
backgroundImgUrl = backgroundImg[backgroundImgIndex];

changeImage();
}, 5000);
changeImage();

请看这里https://codepen.io/vyspiansky/pen/jOqqNmQ

最新更新