编程语言
首页 > 编程语言> > JavaScript-Tab栏切换

JavaScript-Tab栏切换

作者:互联网

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/commen.css">
</head>
<style>
    ul li{
        width: 100px;
        height: 30px;
        border: 1px solid #000;
        float: left;
    }
    li.cur{
        background-color: red;
    }
    div.item{
        width: 300px;
        height: 300px;
        border: 1px solid #000;
        display: none;
    }
    div.cur{
        display: block;
    }
</style>
<body>
    <!-- 要把两个元素放到一个div里面 -->
    <div>
        <ul class="clear">
            <li class="cur">1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <div class="ph">
            <div class="item cur">111</div>
            <div class="item">222</div>
            <div class="item">333</div>
        </div>
    </div>
    <div>
        <ul class="clear">
            <li class="cur">1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <div class="ph">
            <div class="item cur">111</div>
            <div class="item">222</div>
            <div class="item">333</div>
        </div>
    </div>
</body>
<script src="/jquery-3.6.0.min.js"></script>
<script>
    $('li').click(function(){ // li标签点击事件
        var i = $(this).index(); // 获取li标签的索引位置
        $(this).addClass('cur').siblings().removeClass('cur'); // li标签添加元素cur同级元素清楚cur
        $(this).parent().siblings('.ph').find('.item').eq(i).addClass('cur').siblings().removeClass('cur');
    });
</script>
</html>

 

理解:

当点击<li>标签时,获取<li>标签的索引位置,让<li>标签添加类cur并让其同级元素清楚cur,

<li>标签查找父级元素<ul>标签,找到class名为ph的同级元素,查找class名为item的子级元素的索引位置并添加类cur同级元素清楚cur

 

标签:元素,cur,标签,JavaScript,li,item,切换,Tab,siblings
来源: https://www.cnblogs.com/sam-zh/p/15351619.html