面向对象的选项卡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .cont{400px;height:300px;border: solid 1px black;margin: 30px auto;}
        .cont ul{margin: 0;padding: 0;list-style: none;display: flex;height: 40px;line-height: 40px;text-align: center;background: #eee;border-bottom: solid 1px black;}
        .cont li{flex: 1;border-right: solid 1px black;}
        .cont li.active{background: red}

        .box p{margin: 0;height: 259px;display: none}
        .box p.active{display: block;}
        .box p:nth-child(1){background: #0a0}
        .box p:nth-child(2){background: #aa0}
        .box p:nth-child(3){background: #0aa}
    </style>
</head>
<body>
    <div class="cont">
        <ul><li class="active">1</li><li>2</li><li>3</li></ul>
        <div class="box">
            <p class="active">内容1内容1内容1内容1内容1内容1</p>
            <p>内容2</p>
            <p>内容3333333333</p>
        </div>
    </div>
</body>
<script>

    // OOA:分析
    //     选项卡:点击对应按钮的时候,切换对应的内容
    //     1.选元素
    //     2.绑定事件
    //     3.找点击的元素的索引
    //     4.根据索引,显示内容

    // OOD:设计
    // function Tab(){
    //     // 1.选元素
    //     // 2.绑定事件
    // }
    // Tab.prototype.init = function(){
    //     // 开始绑定,绑定好了之后,被触发
    //         // 3.找点击的元素的索引
    //         // 4.根据索引,显示内容
    // }
    // Tab.prototype.display = function(){
    //     // 显示呗
    // }

    // OOP:编程(填充代码)
    function Tab(){
        // 1.选元素
        this.li = document.querySelectorAll(".cont li");
        this.p = document.querySelectorAll(".cont p");
        // 2.绑定事件
        this.init();
    }
    Tab.prototype.init = function(){
        var that = this;
        // 开始绑定,绑定好了之后,被触发
        for(var i=0;i<this.li.length;i++){
            this.li[i].index = i;
            this.li[i].onclick = function(){
                // 3.找点击的元素的索引
                that.abc = this.index;//被点击的那个索引
                // 4.根据索引,显示内容
                that.display();
            }
        }
    }
    Tab.prototype.display = function(){
        // 显示呗
        for(var i=0;i<this.li.length;i++){
            this.li[i].className = "";
            this.p[i].className = "";
        }
        this.li[this.abc].className = "active";
        this.p[this.abc].className = "active";
    }

    new Tab();

</script>
</html>
原文地址:https://www.cnblogs.com/hy96/p/11456135.html