温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-22 05:24:33 来源:网络 阅读:469 作者:DanielYue 栏目:web开发

    现在的页面上几乎都要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 ></p>
            <div class="box" >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 ></p>
            <div class="box" >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点击的对象找到父元素,从父元素再去找对应的显示块就解决了,当然还要优化,只是呈现了最简单的代码实现了基本效果仅供展示。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI