js面向对象实现Tab切换

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input {
            width: 200px;
            height: 20px;
            background: white;
        }

        input.active {
            background: yellow;
        }

        #div1 div {
            width: 200px;
            height: 200px;
            background-color: #cccccc;
            display: none;
        }
    </style>
</head>

<body>
    <div id="div1">
        <input type="button" value="a">
        <input type="button" value="b">
        <input type="button" value="c">
        <div class="dv">a</div>
        <div class="dv">b</div>
        <div class="dv">c</div>
    </div>
</body>
<script>
    
    window.onload = function () {
        new TabSwitch('div1')
    }
    function TabSwitch(id) {
        var _this = this;
        var oDiv1 = document.getElementById(id);

        this.bTn = document.getElementsByTagName('input');
        this.aDiv = document.getElementsByClassName('dv');

        document.getElementsByTagName('input')[0].className = 'active';
        document.getElementsByClassName('dv')[0].style.display = 'block';

        for (var i = 0; i < this.bTn.length; i++) {
            this.bTn[i].index = i;
            this.bTn[i].onclick = function () {
                _this.fnClick(this);
            }
        }
    };
    
    TabSwitch.prototype.fnClick = function (oBtn) {
        for (var i = 0; i < this.bTn.length; i++) {
            this.bTn[i].className = '';
            this.aDiv[i].style.display = 'none';
        }
        oBtn.className = 'active';
        this.aDiv[oBtn.index].style.display = 'block';
    }
</script>

</html>

 

posted @ 2020-05-28 16:23  YH丶浩  阅读(369)  评论(0编辑  收藏  举报