原生JS選項卡(Tab頁切換)

使用原生JS實現選項卡功能。
效果:


image.png

原理:全部隱藏,選擇哪個哪個顯示。
代碼如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }
            #all{
                width: 600px;
                margin: 50px auto;
                height: 500px;
                border: 2px red solid;
                position: relative;
            }
            #all #tab li{
                list-style: none;
                float: left;
                width: 200px;
                height: 50px;
                line-height: 50px;
                text-align: center;
                font-size: 30px;
                font-weight: 700;
            }
            #all .con{
                width: 580px;
                height: 430px;
                position: absolute;
                top: 60px;
                left: 10px;
                display: none;
            }
        </style>
        <script type="text/javascript">
            window.onload = function(){
                var tab = document.getElementById("tab");
                var lis = tab.getElementsByTagName('li');//獲得標簽li的數組
                var cons = document.getElementsByClassName('con');//獲得下面內容div的數組
                for(var i=0;i<lis.length;i++){
                    lis[i].num = i;//給對象添加屬性,賦值用于標記
                    lis[i].onmousemove = function(){
                        //div先全部隱藏
                        for(var j = 0;j<cons.length;j++){
                            cons[j].style.display = 'none';
                        }
                        //顯示與鼠標所在li對應位置的div
                        cons[this.num].style.display = 'block';
                    }
                }
            }
        </script>
    </head>
    
    <body>
        <div id="all">
            <ul id="tab">
                <li style="background: greenyellow;">軍事</li>
                <li style="background: palevioletred;">民生</li>
                <li style="background: paleturquoise;">娛樂</li>
            </ul>
            <div class="con" style="display:block;background: greenyellow;"></div>
            <div class="con" style="background: palevioletred;"></div>
            <div class="con" style="background: paleturquoise;"></div>
        </div>
    </body>
</html>

如有問題歡迎交流。

如轉載請注明出處,謝謝!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容