利用js实现选项卡效果

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            border: 1px solid;
            display: none;
        }

        .red {
            background-color: red;
        }

        .show {
            display: block;
        }
    </style>
</head>

<body>
    <input type="button" class="red" value="按钮1"></input>
    <input type="button" value="按钮2"></input>
    <input type="button" value="按钮3"></input>
    <div class="show">内容1</div>
    <div>内容2</div>
    <div>内容3</div>
</body>

</html>
<script>
    var oBtns = document.querySelectorAll("input");
    var oDiv = document.querySelectorAll("div");
    //实现排他,并获取索引
    for (var i = 0; i < oBtns.length; i++) {
        oBtns[i].onclick = function () {
            for (var j = 0; j < oBtns.length; j++) {
                oBtns[j].classList.remove("red"); //再设置样式前先取消所有样式
            }
            this.classList.add("red"); //设置点击的样式
            this.setAttribute("index", i);
            var index=parseInt(this.getAttribute("index")) ;
            for(var x = 0; x < oBtns.length; x++){
            oDiv[index].classList.remove("show")
            }
            oDiv[index].classList.add("show")
        }
    }
</script>

基本的结构是这样的,大家可以根据需求自行修改代码以实现效果

猜你喜欢

转载自blog.csdn.net/qq_52477159/article/details/126574309