js实现轮播图改进
2016-12-26 本文已影响44人
LOOK_LOOK
改进处
(1)自动切换
(2)鼠标移到图片和左右图标上时停止自动切换
(3)鼠标移开时继续自动切换
涉及的知识点
(1)定时器
setInterval(function_name,1000)
或者setInterval("function_name()",1000)
;
(2)取消定时器
id=setInterval(function_name,1000);
clearInterval(id);
(3)给组件绑定函数
var img = document.getElementById("img");
//stop是函数名
img.onmouseout=stop;
script.js
代码
window.onload=function (){
var img = document.getElementById("img");
var spans = document.getElementsByTagName("span");
var images = ["a.jpg", "b.jpg", "c.jpg", "d.jpg"];
var left = spans[0];//向左
var right = spans[1];//向右
var index=0;//下标
var id=0;//计时器id
/*向右切换*/
function changeImg(){
if(index==images.length-1||index>images.length-1){
index=-1;
}
img.src=images[++index];
show.value = index;
}
id=setInterval(changeImg,1000);//初始化计时器
function start(){//开始计时
clearInterval(id);
}
function stop(){//停止计时
id=setInterval(changeImg,1000);
}
/*给各组件绑定响应事件,鼠标移到图片、左右切换图标时停止计时,不在这三者上面时重新开始自动切换*/
img.onmouseover=start;
img.onmouseout=stop;
right.onclick=changeImg;
right.onmouseover=start;
right.onmouseout=stop;
left.onmouseover=start;
left.onmouseout=stop;
/*向左切换*/
left.onclick=function (){
if(index==0){
index=images.length;
}
img.src=images[--index];
show.value = index;
}
}