老师,轮播图自动播放实现问题
来源:3-5 定时器
慕虎5004390
2019-07-18 16:53:42
var timer=null,
index=0,
pics = ById("banner").getElementsByTagName("div"),
size = pics.length,
dots = ById("dots").getElementsByTagName("span"),
banner=ById("banner"),
prev=ById("prev"),
next=ById("next");
function addHander(Element,type,hander){
if(Element.addEventListener){
Element.addEventListener(type,hander,false);
}
else if(Element.attachEvent){
Element.addEventListener("on"+type,hander);
}
else{
Element["on"+type]=hander;
}
}
function ById(id){
if(typeof(id)==="string") {return document.getElementById(id);}
else {return id;}
}
function changeimg(){
for(var i=0,len=pics.length;i<len;i++){
pics[i].style.display="none";
dots[i].className="";
}
pics[index].style.display="block";
dots[index].className="active";
}
addHander(next,"click",function(){
index++;
if(index>=3) index=0;
changeimg();
})
addHander(prev,"click",function(){
index--;
if(index<0) index=2;
changeimg();
})
for(var j=0,len1=dots.length;j<len1;j++){
dots[j].setAttribute("dotsId",j);
addHander(dots[j],"click",function(){
index=this.getAttribute("dotsId");
changeimg();
})
}
function stopAtoplay(){
if(timer){
clearInterval(timer);
}
}
function startAtoplay() {
/*timer=setInterval(function(){
index++;
if(index>=3) {index=0;}
changeimg();
},3000)*/
timer = setInterval(function(){
console.log(index);
index++;
if(index >= size){
index = 0;
}
changeimg();
},3000)
}
addHander(banner,"mouseout",startAtoplay);
addHander(banner,"mouseover",stopAtoplay);
html和css与老师代码相同,js轮播图自动播放时,要等待很长时间才开始自动播放,有时甚至不会播放,麻烦老师帮我找一下原因。
1回答
同学你好,
1、自动播放事件需要提前调用才可以自动轮播,否则鼠标移入移出之后才可以轮播。
2、需要将移入停止轮播,移出继续轮播事件绑定在最外层大盒子上,这样点击左右按钮以及小圆点的时候轮播才能停止,否则是同时进行的。
参考如下:

可以修改测试下,祝学习愉快!
相似问题