[英]call EventListener with setInterval()
我的任务是在幻灯片中制作几张图片,如果在5秒钟内不单击前进和后退按钮(代码中的id = right和id = left),它应该会自动前进,我成功了,但是我觉得代码太多了。
var counter = 1;
$('#left').on('click', function peter() {
clearInterval(time);
time = setInterval(function () {
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter++;
if(counter === 4){
counter = 1;
}
id = '#' + counter;
$(id).attr('class', 'visible');
},3000);
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter--;
if (counter === 0) {
counter = 3;
}
id = '#' + counter;
$(id).attr('class', 'visible');
});
$('#right').on('click', function () {
clearInterval(time);
time = setInterval(function () {
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter++;
if(counter === 4){
counter = 1;
}
id = '#' + counter;
$(id).attr('class', 'visible');
},3000);
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter++;
if(counter === 4){
counter = 1;
}
id = '#' + counter;
$(id).attr('class', 'visible');
});
var time = setInterval(function peter() {
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter++;
if(counter === 4){
counter = 1;
}
id = '#' + counter;
$(id).attr('class', 'visible');
},3000);
因此,您可以看到的问题是,我几乎清除了setInterval()3次,在代码中排第1次,然后每次在eventListeners中将其清除,以重置它。 我的问题是:有没有办法清除它一次并调用timeListener这样的eventListener time(call listnener for id='right')
的listnener time(call listnener for id='right')
,然后在事件列表中像clearInterval(a)
一样将其重置? 无需重新输入。
var counter = 1;
var time;
function intervalFunction(offset)
{
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter += offset;
if(counter > 4)
counter = 1;
else if(counter < 1)
counter = 4;
id = '#' + counter;
$(id).attr('class', 'visible');
}
function startInterval(offset){
if(time)
clearInterval(time);
intervalFunction(offset);
time = setInterval(function () {
intervalFunction(1);
},3000);
}
$('#left').on('click', function peter() {
startInterval(-1);
});
$('#right').on('click', function () {
startInterval(1);
});
startInterval(1);
我不确定是否会这样做。 实际上没有先测试它。 但是您可以将所有冗余工作组合到一个您将要调用的函数中。 我在函数中添加了clicktype参数,并使用它来确定它应该增加还是减少计数器的值。
我还将setInterval修改为setTimeout,因为在此设置中,每次都会清除并重置调用。
var counter = 1;
var timeoutdelay = 3000;
function OnChangeSlide(clicktype) {
clearTimeout(time);
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter = counter + (clicktype=='#left' ? -1 : 1);
if (counter === 0) {
counter = 3;
} else if (counter === 4) {
counter = 0;
}
id = '#' + counter;
$(id).attr('class', 'visible');
time = setTimeout(function() { OnChangeSlide('#right'); }, timeoutdelay);
}
$('#left').on('click', function() { OnChangeSlide('#left'); } );
$('#right').on('click', function() { OnChangeSlide('#right'); } );
time = setTimeout(function(){ OnChangeSlide('#right'); }, timeoutdelay);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.