我有一个 div,其背景图像每 5 秒更改一次,并且我有一个下一个按钮,该按钮应清除 setInterval 计时器并将背景更改为下一个并再次触发 setInterval 但是当我单击下一个按钮时,它会将背景更改为下一个,但不会再次触发 setInterval。
HTML 代码:
<div id="slideshow">
</div>
<a href="" id="arrow_right"><i class="fa fa-angle-right"></i></a>
CSS 代码:
#slideshow {
height:100%;
width:100%;
background: url(../css/img/bg/slide1.jpg) no-repeat;
background-position: center center;
background-size: cover;
}
JS 代码:
$(document).ready(function() {
var i = 1;
function bgrepeat(x){
if(typeof(x)==='undefined') {
$('#slideshow').fadeOut(500, function () {
$('#slideshow').css('background-image','url(ui/css/img/bg/slide' + i + '.jpg)');
$('#slideshow').fadeIn(500);
});
i++;
if(i == 5) {
i = 1;
}
} else {
$('#slideshow').fadeOut(500, function () {
$('#slideshow').css('background-image','url(ui/css/img/bg/slide' + x + '.jpg)');
$('#slideshow').fadeIn(500);
});
x++;
if(x == 5) {
x = 1;
}
}
};
var timer = setInterval(bgrepeat , 5000);
var bg = $('#slideshow').css('background-image');
bg = bg.split('slide');
var bgpath = bg[1];
bgpath = bgpath.replace('.jpg")','');
bgpath = parseInt(bgpath,10);
$('#arrow_right').click(function(e) {
e.preventDefault();
bgpath++;
if(bgpath == 5) {
bgpath = 1;
}
$('#slideshow').fadeOut(500, function () {
$('#slideshow').css('background-image','url(ui/css/img/bg/slide' + bgpath + '.jpg)');
$('#slideshow').fadeIn(500);
});
clearInterval(timer);
timer2 = setInterval(bgrepeat(bgpath) , 5000);
});
});
最佳答案
您需要将函数传递给 setInterval
,而不是其调用的结果。
timer2 = setInterval(function() {
bgrepeat(bgpath)
}, 5000);
关于javascript - 单击时触发 setInterval 发生一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25281392/