美文网首页
Javascript面向对象方式实现Tab选项卡

Javascript面向对象方式实现Tab选项卡

作者: iDevOps | 来源:发表于2019-09-18 18:44 被阅读0次

效果

Tab选项卡

代码

  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tab选项卡</title>
    <link rel="stylesheet" href="css/index.css">
</head>
<body>


<div id="tab">

    <!--header-->
    <div id="tab-header">
        <ul>
            <li class="selected">one</li>
            <li>two</li>
            <li>three</li>
            <li>four</li>
            <li>five</li>
        </ul>
    </div>

    <!--content-->
    <div id="tab-content">
        <div class="dom" style="display: block">
            one
        </div>
        <div class="dom">
            two
        </div>
        <div class="dom">
            three
        </div>
        <div class="dom">
            four
        </div>
        <div class="dom">
            five
        </div>
    </div>
</div>


<script src="./js/tab.js"></script>
<script>
    var tabs = new Tabs();
    tabs.init();
</script>

</body>
</html>
  • index.css
*{
    padding: 0;
    margin: 0;
}

ul{
    list-style: none;
}

#tab{
    width: 498px;
    height: 130px;
    border: 1px solid #9d9d9d;
}

/*tab-header*/
#tab-header{
    height: 33px;
    background-color: #e8e8e8;
    position: relative;
}

#tab-header ul{
    width: 501px;
    position: relative;
    left: -1px;
}

#tab-header ul li{
    float: left;
    width: 98px;
    height: 33px;
    text-align: center;
    line-height: 33px;
    padding: 0 1px;
    border-bottom: 1px solid #9d9d9d;
    cursor: pointer;
}

#tab-header ul li.selected{
    background-color: white;
    border-bottom: 0;
    border-left: 1px solid #9d9d9d;
    border-right: 1px solid #9d9d9d;
    padding: 0;
}

#tab-header ul li:hover{
    color: black;
    font-weight: bolder;
}

/*tab-content*/
#tab-content{
    padding-top: 15px;
}

#tab-content .dom{
    display: none;
}


  • tab.js
//构造函数
function Tabs() {
    //获取tab-header下所有li
    this.tab_header_lis = document.getElementById('tab-header').getElementsByTagName('li');
    //获取tab-content下所有class为dom的div
    this.tab_content_doms = document.getElementById('tab-content').getElementsByClassName('dom');
}

//原型方法
Tabs.prototype = {
    init: function () {
        var that = this;
        for(var i=0; i<this.tab_header_lis.length; i++){
            //1. 给所有li设置索引
            this.tab_header_lis[i].index = i;
            //2. 给所欲的li绑定鼠标事件
            this.tab_header_lis[i].onmouseover = function () {
                for(var j=0; j<that.tab_header_lis.length; j++){
                    that.tab_header_lis[j].className = '';
                    that.tab_content_doms[j].style.display = 'none';
                }
                this.className = 'selected';
                that.tab_content_doms[this.index].style.display = 'block';
            }
        }
    }
}

相关文章

网友评论

      本文标题:Javascript面向对象方式实现Tab选项卡

      本文链接:https://www.haomeiwen.com/subject/cdfgyctx.html