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>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值