用js实现一个基本的切换功能

132 阅读1分钟

这是一个基本的切换功能,当然也有更好的,只是为了能更好的方便自己,有更好的方法也可以分享一下。欢迎留言!

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

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box
        }

        div {
            width: 70%;
            margin: 100px auto
        }

        ul {
            list-style: none;
            overflow: hidden
        }

        .tabs li {
            float: left;
            width: 100px;
            text-align: center;
            line-height: 30px;
            background: #f60;
            border: 1px solid #f60;
            border-bottom: none;
            cursor: pointer;
        }

        .tabs li:hover {
            background: #fff;
        }

        .tabs li.active {
            background: #fff;
        }

        .content {
            position: relative;
            width: 400px;
            ;
            height: 300px;
            border: 1px solid #f60;
            border-top: none;
        }

        .content li {
            width: 100%;
            height: 100%;
            position: absolute;
            padding: 10px;
            display: none;
        }
    </style>
</head>

<body>
    <div>
        <ul class="tabs" id="tabs">
            <li class="active">选项1</li>
            <li>选项2</li>
            <li>选项3</li>
            <li>选项4</li>
        </ul>
        <ul class="content" id="content">
            <li style="display: block">内容1</li>
            <li>内容2</li>
            <li>内容3</li>
            <li>内容4</li>
        </ul>
    </div>

    <script>
        //    普通方法实现一个选项卡切换
        var tabs = document.getElementById("tabs");
        var tablist = tabs.children;
        var content = document.getElementById("content");
        var conlist = content.children;

        for (i = 0; i < tablist.length; i++) {
            tablist[i].index = i;  // tablist[i]增加index属性 ,属性值为该项的下标
            tablist[i].onclick = function () {
                for (j = 0; j < conlist.length; j++) {
                    tablist[j].className = "";
                    conlist[j].style.display = "none";
                }
                this.className = "active";
                conlist[this.index].style.display = "block";
            }
        }

    </script>
</body>

</html>