使用面向对象编程封装TAB切换

112 阅读1分钟
CSS部分
*{
margin: 0;
padding: 0;
list-style: none;
}
#box1,
#box2{
    width: 300px;
    height: 400px;
    overflow: hidden;
    border: 1px solid #000;
    margin: 10px auto;
}
.nav{
    width: 100%;
    height: 99px;
    overflow: hidden;
    border-bottom: 1px solid #000;
}
.nav>li{
    float: left;
    width: 100px;
    height: 100%;
    text-align: center;
    line-height: 100px;
}
.nav>.active{
    color: #fff;
    background-color: pink;
}
.item{
    width: 100%;
    height: 300px;
    text-align: center;
    line-height: 300px;
    font-size: 32px;
    display: none;
}
.show{
    display: block;
}
</style>
HTML部分
<body>
    <div id="box1">
        <ul class="nav">
        <li class="active">1</li>
        <li>2</li>
        <li>3</li>
        </ul>
        <div class="item show">内容1</div>
        <div class='item'>内容2</div>
        <div class='item'>内容3</div>
        </div>

        <div id="box2">
        <ul class="nav">
        <li class="active">1</li>
        <li>2</li>
        <li>3</li>
        </ul>
        <div class="item show">内容1</div>
        <div class='item'>内容2</div>
        <div class='item'>内容3</div>
    </div>
JS部分
    <script type="text/javascript">
        var box1 = document.getElementById('box1');

        var box2 = document.getElementById('box2');

        //面向对象写法
        //1、创建一个构造函数(父类)
        function Tab(obj){
        this.obj = obj;
        //获取所需元素
        this.navs = this.obj.getElementsByTagName('li');
        this.items = this.obj.getElementsByClassName('item');
        //this.init = function (){}
        }

        //2、把点击事件变成属性
        Tab.prototype.init = function (){
        //2-1、改变this指向(因为this指向对象)
        var _this = this;
        for(var i = 0; i < this.navs.length; i++){
        this.navs[i].onclick = (function (index){
        //2-2、返回内部函数(闭包原理)
        return function (){
        //2-3、调用执行赋值函数
        _this.changes(this, index);
        }
        })(i)
        }
        };

        //3、把函数变成方法
        Tab.prototype.changes = function (tag, index){
        //3-1、清空所有默认项
        for(var i = 0; i < this.navs.length; i++){
        this.navs[i].className = '';
        this.items[i].className = 'item';
        }
        tag.className = 'active';
        this.items[index].className = 'item show';
        }

        //4、将对象实例化
        var tab1 = new Tab(box1);
        tab1.init();

        var tab2 = new Tab(box2);
        tab2.init();
    </script>
</body>

注释: 使用面向对象编程封装Tab切换的话,复用性强。比普通函数封装的要好用。