JS面向对象编程(实现tab选项卡)案例

一个非常简单的tab案例

点击切换不同的页面,下面是代码

 <div id="box1">
        <span class="red">111</span>
        <span>222</span>
        <span>333</span>

        <div style="display: block;">TVT</div>
        <div>o((>ω<))o< /div>
        <div>l(qwq)o</div>
 </div>
        <script>
            //创建对象
            function Fun (id) {
                this.box = document.getElementById(id);
                this.span = this.box.getElementsByTagName('span');
                this.div = this.box.querySelectorAll('div');
            }
            //点击事件
            Fun.prototype.init = function () {
                // 保存当前的this指向
                var _this = this
                for (var i = 0; i < this.span.length; i++) {
                    //给span加一个非原有属性,用来统一和div出现的下标值
                    this.span[i].setAttribute('index', i)
                    //给每一个span都设置点击事件
                    this.span[i].onclick = function () {
                        console.log(this);
                        // 调用
                        _this.change(this)
                    }
                }
            }
            //变色和便内容
            Fun.prototype.change = function (obj) {

                for (var i = 0; i < this.span.length; i++) {
                    this.span[i].className = ""
                    this.div[i].style.display = 'none'
                }
                obj.className = 'red'
                this.div[obj.getAttribute('index')].style.display = 'block'
            }
            var a = new Fun('box1')
            a.init()
        </script>

下面是样式代码

  <style>
        #box1 {
            width: 500px;
            height: 500px;
            display: flex;
            flex-wrap: wrap;
        }

        span {
            display: block;
            width: 140px;
            height: 40px;
            margin: 0 10px;
            text-align: center;
            line-height: 40px;
            border: 1px solid;
        }

        #box1 div {
            width: 500px;
            height: 400px;
            border: 1px solid;
            display: none;
            text-align: center;
            line-height: 400px;
            background-color: pink;
        }

        .red {
            background-color: rgb(193, 190, 190);
        }
    </style>

猜你喜欢

转载自blog.csdn.net/al7lin/article/details/129020560
今日推荐