js实现简单的tab切换

页面分析:
三个按钮:三个内容;点击不同的按钮显示不同的内容。
初始状态:3个按钮始终显示;3个内容只是显示一个;其它默认隐藏装填;

css样式代码

 * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .content {
            width: 100px;
            height: 100px;
            background: #ff3333;
            border: 1px black solid;
            display: none;
        }

        .active {
            display: block;
        }

html代码

<body>
<button>tabONE</button>
<button>TABtwo</button>
<button>TabThree</button>
<div class="content active">111</div>
<div class="content">222</div>
<div class="content">3333</div>
</body>

js代码

var btn = document.getElementsByTagName('button');
        var content = document.getElementsByClassName('content');
        for (var i = 0; i < btn.length; i++) {
            // 给button 对象添加index属性,目的是为了区分点击的是哪个btn
            btn[i].index = i // 0 1 2
            //    console.log(btn[i])
            // 遍历了每一个按钮;并且都添加了点击事件,btn[i]获取到时button对象
            btn[i].onclick = function () {
                // 遍历每每一个content ;目的;初始均是隐藏状态
                for (var j = 0; j < content.length; j++) {
                    content[j].style.display = 'none';
                }
                // this,index = 0,1,2 点击哪个按钮让其对应的内容为显示状态
                content[this.index].style.display = 'block'
                console.log(this); // this 指的的当前这个方法的对象;button 
            }
        }

        // btn[1].onclick = function () {
        //     content[1].style.display = 'block';
        //     content[0].style.display = 'none'
        // }

        var btn = [
            {
                index: 0
            },
            {
                index: 1
            },
            {
                index: 2
            }
        ]

猜你喜欢

转载自blog.csdn.net/qq_43294510/article/details/88319409