当前位置:   article > 正文

html js实现tab代码,原生JS代码实现自动TAB切换(原创)

html+js写一个移动端的tab

//声明变量

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);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/69357
推荐阅读
相关标签
  

闽ICP备14008679号