一段jquery代码搞定多个tab效果

    现在的页面上几乎都要tab切换甚至不止一个,早有想法尝试用一段代码控制所有tab的方法,自己尝试了一下。里面有几个要点抓住就好了。

           <style>
            .wrap{
                width:100%;
                height:800px;
                position: relative;
            }
            .wrap2{
                width:100%;
                height:800px;
                position: relative;
            }
            .title{
                width:200px;
                height:50px;
                background-color:#ccc;
                display:inline-block;
            }
            .box{
                width:600px;
                height:300px;
                border:1px solid red;
                display:none;
                position: absolute;
            }
        </style>
</head>
<body>
    
    <div class="wrap">
        <p class="title">1</p>
        <p class="title">2</p>
        <p class="title">2</p>
        <p style="clear:both"></p>
            <div class="box" style="display:block">a</div>
            <div class="box">b</div>
            <div class="box">c</div>        
    </div>
        <div class="wrap2">
        <p class="title">1</p>
        <p class="title">2</p>
        <p class="title">2</p>
        <p style="clear:both"></p>
            <div class="box" style="display:block">a</div>
            <div class="box">b</div>
            <div class="box">c</div>        
    </div>    <script>    
    $(function(){
        
        $('.title').click(function(){
            var $this=$(this);
            var $pare=$this.parent();
            //alert($this)
            //alert($pare.find(".box").eq($this));
            $pare.find(".box").eq($this.index()).show().siblings(".box").hide();
        })
    })
    </script>

    代码思路:1,共同点有什么?结构一样,比如tab的切换块和下面的显示块都是一样的结构,他们下面显示块的下标总是与上面的下标一样。换句话说,他们的this.index值都可以直接从上面的切换块传值。

2,有一个问题就是他们都是部门的代码结构块,怎么能只用this.index传递一个下标就可以解决呢,或者会出现一个经常会出现的问题,就是一个切换,所有的tab都会切换。但是有一个不同点是什么呢?就是他们的父亲不一样,所以这就是问题所在,我们可以用this点击的对象找到父元素,从父元素再去找对应的显示块就解决了,当然还要优化,只是呈现了最简单的代码实现了基本效果仅供展示。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章