1. 程式人生 > 實用技巧 >選項卡原生js案列

選項卡原生js案列

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .btn {
            width: 70px;
            box
-shadow: 5px 5px 5px rgba(194, 187, 82, 0.712); } .active { background: pink; } .wrap-main>div { width: 200px; height: 200px; border: 1px solid #333; font-size: 30px; font-weight: 900px; text
-align: center; line-height: 200px; display: none } .wrap-main>div>img { width: 250px; height: 250px; } </style> </head> <body> <div class="wrap"> <div class="wrap-head"> <button class
="btn active">1</button> <button class="btn">2</button> <button class="btn">3</button> </div> <div class="wrap-main"> <div class="content" style="display: block;"><img src="./01.jpg" alt=""></div> <div class="content"><img src="./02.jpg" alt=""></div> <div class="content"><img src="./05.jpg" alt=""></div> </div> </div> <div class="wrap"> <div class="wrap-head"> <button class="btn active">1</button> <button class="btn">2</button> <button class="btn">3</button> </div> <div class="wrap-main"> <div class="content" style="display: block;"><img src="./01.jpg" alt=""></div> <div class="content"><img src="./02.jpg" alt=""></div> <div class="content"><img src="./05.jpg" alt=""></div> </div> </div> <div class="wrap"> <div class="wrap-head"> <button class="btn active">1</button> <button class="btn">2</button> <button class="btn">3</button> </div> <div class="wrap-main"> <div class="content" style="display: block;"><img src="./01.jpg" alt=""></div> <div class="content"><img src="./02.jpg" alt=""></div> <div class="content"><img src="./05.jpg" alt=""></div> </div> </div> <script> function tab(wrap) { var btns = wrap.querySelectorAll("button"); var divs = wrap.querySelectorAll(".content"); for (var i = 0; i < btns.length; i++) { btns[i].index = i;//自定義屬性,作為下標 btns[i].onclick = function () { for (var i = 0; i < btns.length; i++) { btns[i].classList.remove("active"); divs[i].style.display = "none"; } this.classList.add("active"); divs[this.index].style.display = "block"; } } } var wraps = document.querySelectorAll(".wrap"); for (var i = 0; i < wraps.length; i++) { tab(wraps[i]); } </script> </body> </html>