1. 程式人生 > >JavaScriptr——Tab欄切換案列

JavaScriptr——Tab欄切換案列

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {

            width: 300px;
            margin: auto;
            display: flex;
            flex-direction: column;
        }

        .hd {
            height: 20px;
            display: flex;
            justify-content: space-between;
            /* align-items: center; */

        }

        .hd .cls {
            background-color: red;
        }

        span {
            background: rgb(245, 241, 13);
            cursor: pointer;

        }

        .bd {
            height: 300px;
            background: red;
        }

        .bd li {
            display: none;
        }

        .bd li.cls {
            display: block;
        }
    </style>
</head>

<body>
    <div class="box" id="box">
        <div class="hd">
            <span class="cls">英雄聯盟</span>
            <span>王者榮耀</span>
            <span>刺激戰場</span>

            <span>QQ飛車</span>
        </div>
        <div class="bd">
            <ul>
                <li class="cls">LOL</li>
                <li>簡單的遊戲</li>
                <li>苟就完事了</li>
                <li>相伴十年</li>
            </ul>
        </div>
    </div>

    <script>
        //獲取最外層div 
        var boxobj = document.getElementById("box");
        //獲取第一個div
        var hdobj = boxobj.getElementsByTagName("div")[0];
        //獲取第二個div
        var bdobj = boxobj.getElementsByTagName("div")[1];

        //獲取第二個div裡面所有的li標籤 
        var list = bdobj.getElementsByTagName("li");

        //獲取第一個div中所有的span標籤
        var spans = hdobj.getElementsByTagName("span");
        //所有的span點選事件
        for (var i = 0; i < spans.length; i++) {
            //在點選每個span標籤之前獲取索引值
            spans[i].setAttribute("index", i)
            spans[i].onclick = function () {
                //先隱藏所有的cls
                for (var j = 0; j < spans.length; j++) {
                    spans[j].removeAttribute("class");
                }
                //點選哪個顯示哪個cls
                this.className = "cls";

                //得到當前點選時的索引值
                var num = this.getAttribute("index");
                for (var k = 0; k < list.length; k++) {
                    //先隱藏所有的
                    list[k].removeAttribute("class")
                }
                //點選當前的顯示cls
                list[num].className = "cls"
            }

        }
    </script>
</body>

</html>