赞
踩
//声明变量
var main = byId("main"),
index = 0,
nav = byId("nav"),
tabs = nav.getElementsByTagName("span"),
banner = byId("banner"),
pics = banner.getElementsByTagName("div"),
len = tabs.length;
//封装getElementById函数
function byId(id) {
return typeof(id) === "string" ? document.getElementById(id) : id;
}
//封装通用事件绑定函数,兼容性写法
function addHandler(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler
}
}
//封装改变图片函数
function changeImg() {
for (var j = 0; j < len; j++) {
tabs[j].className = "";
pics[j].style.display = "none"
}
tabs[index].className = "active";
pics[index].style.display = "block"
}
//封装定时器函数
function startAutoPlay() {
timer = setInterval(function() {
index++;
if (index >= len) {
index = 0;
}
changeImg();
}, 3000)
}
//封装清除定时器函数
function stopAutoPlay() {
if (timer) {
clearInterval(timer)
}
}
//鼠标经过tab变颜色,且背景图变换
for (var i = 0; i < len; i++) {
tabs[i]["data-id"] = i;
addHandler(tabs[i], "mouseover", function() {
index = this["data-id"];
changeImg();
})
}
//开启自动轮播
startAutoPlay();
//鼠标滑入main,停止自动轮播
addHandler(main, "mouseover", stopAutoPlay);
//鼠标离开main,重新开启自动轮播
addHandler(main, "mouseout", startAutoPlay);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。