DOM经典例子(选项卡1)

实现效果:
在这里插入图片描述
方法1:
代码:

<!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;
        }

        #main {
            width: 300px;
            margin: 50px auto 0;
        }

        #menu ul li {
            list-style: none;
            float: left;
            width: 100px;
            height: 50px;
            background-color: chartreuse;
            text-align: center;
            line-height: 50px;
        }

        #contain ul li {
            width: 300px;
            height: 400px;
            list-style: none;
            background-color: pink;
            display: none;
        }

        #menu ul .active {
            background-color: crimson;
        }

        #contain ul .active {
            display: block;
        }
    </style>
</head>

<body>
    <div id="main">
        <div id="menu">
            <ul>
                <li class="active">菜单1</li>
                <li>菜单2</li>
                <li>菜单3</li>
            </ul>
        </div>
        <div id="contain">
            <ul>
                <li class="active">数学</li>
                <li>语文</li>
                <li>英语</li>
            </ul>
        </div>
    </div>

    <script>
        var oMenu = document.getElementById("menu");
        var oLi1 = oMenu.getElementsByTagName("li");

        var oCon = document.getElementById("contain");
        var oLi2 = oCon.getElementsByTagName("li");

        for (var i = 0; i < oLi1.length; i++) {
            oLi1[i].index = i;
            oLi1[i].onclick = function () {
                for (var j = 0; j < oLi1.length; j++) {
                    oLi1[j].className = " ";
                    oLi2[j].className = " ";
                }

                this.className = "active";
                oLi2[this.index].className = "active";
            }
        }
    </script>
</body>

</html>
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页