用js面向对象写的选项卡


<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
            list-style: none;
        }           
        #box span, #box2 span{
            width: 95px;
            height: 40px;
            background: darkgoldenrod;
            float: left;
            margin-right: 5px;
            text-align: center;
            line-height: 45px;
            cursor: pointer;
        }
        #box p,#box2 p{
            width: 295px;
            height: 250px;                          
            margin-top: 40px;
            display: none;
            border:1px solid firebrick;
        }


        .active {
            color: white;
            background:grey;
        }
    </style>
</head>

<body>
    <div id="box">
        <span class="active">选项卡1</span>
        <span>选项卡2</span>
        <span>选项卡3</span>
        <p style="display: block;">内容1</p>
        <p>内容2</p>
        <p>内容3</p>
    </div>
    <div id="box2">
        <span class="active">选项卡1</span>
        <span>选项卡2</span>
        <span>选项卡3</span>
        <p style="display: block;">内容1</p>
        <p>内容2</p>
        <p>内容3</p>
    </div>
    <script type="text/javascript">

// var oBox = null;
// var oP = null;
var _this = this;
window.onload = function() {
new Tab(‘box’);new Tab(‘box2’);
};

        function Tab(id) {
            this.oBox = document.getElementById(id)
            this.oP = this.oBox.getElementsByTagName('p');
            //          console.log(oP)
            var _this = this;
            this.oSpan = this.oBox.getElementsByTagName('span');
            for (var i = 0; i < this.oSpan.length; i++) {
                this.oSpan[i].index = i;                                        
                this.oSpan[i].onclick = function(){
                    _this.click(this);                      
                };
            };
        };

        // 将嵌套的函数抽取出来,作为方法
        Tab.prototype.click = function(btn) { // 这里btn是个参数
            for (var i = 0; i < this.oSpan.length; i++) {
                this.oSpan[i].className = '';
                this.oP[i].style.display = 'none';
            };
            //btn是要和span的当前的this保持一致
            //this.className = 'active'; 这里的this是要改成属性this,但是改成this后就会和其他
            //的this冲突,所以这里的this要传参数btn进来        
            btn.className = 'active';
            this.oP[btn.index].style.display = 'block';
        };

    </script>
</body>

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值