我有一种滑块,其元素定义在标签下方,如下所示:
<div class="content-switcher" id="Content1">
我还有Content2和Content3,在其中,我还有一些其他代码可供显示。然后在页面顶部我有这样的事情:
<div class="progress-container">
<a href="" class="item-number" onclick="selectStep(1); return false;">1</a>
<a href="" class="item-number" onclick="selectStep(2); return false;">2</a>
<a href="" class="item-number" onclick="selectStep(3); return false;">3</a>
<div class="progress-selected"></div>
</div>
我的selectStep函数定义如下:
function selectStep(n){
if(n==1){
$(".progress-selected").animate({marginLeft: '5px'},300);
}else if(n==2){
$(".progress-selected").animate({marginLeft: '72px'},300);
}else if (n==3){
$(".progress-selected").animate({marginLeft: '132px'},300);
}
$(".content-switcher").hide();
$("#Content"+n).fadeIn();
}
所以关键是,当我打开页面时,它会显示滑块的第一张幻灯片,这对我来说没问题,如果我点击数字就可以更改幻灯片,但我希望在停留3秒后在第一张幻灯片中,我希望它自动移动到第二张然后第三张,然后再次返回第一张,并继续这样永久。我想我需要使用类似setTimeout的东西,但不知道如何实现它。请注意它应该工作onload,我的意思是当页面加载。有什么想法吗?
答案 0 :(得分:1)
您需要使用window.setInterval
而不是setTimeout
。有些东西;
// set the variable which holds the number of steps/slides you have
var totalSteps = 3;
// set the current selected step, default is the first slide.
var selectedStep = 1;
// assign this to a variable so you can use later
var myInterval = null;
var start = function(){
myInterval = window.setInterval(function(){
// increment the step
selectedStep++;
// check that we are not attempting to select a step that doesn't exist
if ( selectedStep > totalSteps ){
// reset back to 1
selectedStep = 1;
}
// call the function with the selected step
selectStep(selectedStep);
}, 3000);
};
如果您想要启动代码,请致电start();
。
如果您想随时取消时间间隔,可以致电window.clearInterval(myInterval);
,然后再次致电start();
重启。
答案 1 :(得分:0)
以下是代码:
var slide_number = 1;
var sliding_speed = 3000;
var max_number_of_slides = 3;
$(document).ready(function() {
setInterval(selectStep(slide_number), sliding_speed);
});
function selectStep(n) {
if (n == 1) {
$(".progress-selected").animate({
marginLeft: '5px'
}, 300);
} else if (n == 2) {
$(".progress-selected").animate({
marginLeft: '72px'
}, 300);
} else if (n == 3) {
$(".progress-selected").animate({
marginLeft: '132px'
}, 300);
}
$(".content-switcher").hide();
$("#Content" + n).fadeIn();
if (slide_number == max_number_of_slides) slide_number = 0;
slide_number = slide_number++;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="progress-container">
<a href="" class="item-number">1</a>
<a href="" class="item-number">2</a>
<a href="" class="item-number">3</a>
<div class="progress-selected"></div>
</div>
&#13;
您应该使用setInterval
而不是setTimeout
。
阅读更多here
答案 2 :(得分:0)
i = $('.item-number').length;
y = 0;
setInterval(function(){
if(y >= i ) { y = 0 }
$('.item-number')[y].click();
y++;
},3000);