含有定时器的tab栏的切换与函数封装

时间:2022-02-22 02:35:12

css 结构:

/* 用通配符清除默认样式减少代码量,实际项目应对用到的标签清除默认样式*/
*{margin: 0;padding: 0;list-style: none;outline: none;}
/* 注意这里.tab设置宽度布局的精妙*/
.tab{width: 398px;height: 200px;border: 1px solid #ddd;margin: 100px auto 0;font-family: 'arial';}
.hd{background: #f7f7f7;height: 30px;line-height: 30px;text-align: center;}
.hd ul{width: 400px;margin-left: -1px;}
.hd li{float: left;width: 98px;padding: 0 1px;border-bottom: 1px solid #ddd;}
.hd li.cur{background: #fff;border-bottom-color: transparent;border-left: 1px solid #ddd;border-right: 1px solid #ddd;padding: 0;}
.hd li.cur a{font-size: 14px;font-weight: 600;color: #f40;}
/* 下面对a的display:block是去除li里面的1px的空白间隙*/
.hd li a{text-decoration: none;color: #666;font-size: 12px;display: block;}
.hd a:hover{text-decoration: none;}
.bd{position: relative;}
.bd li{text-indent: 2em;line-height: 80px;height: 269px;position: absolute;top: 0;left: 0;width: 100%;display: none;}
.bd li.cur{display: block;}

html 结构:

<div class="tab" id='tab'>
    <div class="hd">
        <ul>
            <li><a href="javascript:;">栏目1</a></li>
            <li><a href="javascript:;">栏目2</a></li>
            <li><a href="javascript:;">栏目3</a></li>
            <li><a href="javascript:;">栏目4</a></li>
        </ul>
    </div>
    <div class="bd">
        <ul>
            <li>这是栏目1区域内容</li>
            <li>这是栏目2区域内容</li>
            <li>这是栏目3区域内容</li>
            <li>这是栏目4区域内容</li>
        </ul>
    </div>
</div>
javascript 结构:

tab('tab'); // 调用函数
function tab(obj) {
    var tab = document.getElementById(obj);
    var hdlis = tab.children[0].getElementsByTagName('li');
    var bdlis = tab.children[1].getElementsByTagName('li');
    var l = hdlis.length;
    hdlis[0].className = 'cur';
    bdlis[0].className = 'cur';
    tab.timer = null;
    for(var i = 0; i < l; i ++) {
        hdlis[i].index = i;
        hdlis[i].onmouseenter = function () {
            var that = this; // 将当前对象存储起来 防止定时器改变this指针
            clearTimeout(tab.timer);
            tab.timer = setTimeout(function () {
                for(var i = 0; i < l; i ++) {
                    hdlis[i].className = '';
                    bdlis[i].className = '';
                }
                that.className = 'cur';
                bdlis[that.index].className = 'cur';
            },300);
        }
        hdlis[i].onmouseleave = function () {
            clearTimeout(tab.timer);
        }
    }
}