个人js学习实例-点击按钮实现按钮背景色变化以及相对应的div变化

版权声明:个人学习小总结 喜欢前端的同学可以加我qq512998324互相交流学习 https://blog.csdn.net/luckybuling/article/details/81676140

效果:

代码:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .box {
            width: 400px;
            margin:100px auto;
            border:1px solid #ccc;
            text-align: center;

        }
        .top{
            margin: 10px 0;
        }
        .bottom div{
            width:100%;
            height: 300px;
            padding-top: 30px;
            background-color: red;
            font-size: 20px;
            font-weight: 600;
            color: #ffffff;
            display: none;
        }
        .red {
            background-color: red;
            color: #ffffff;
        }

    </style>
    <script>
        window.onload = function(){
//            获取6个按钮赋给数组btns
            var btns = document.getElementsByTagName("button");
            //            获取id为divs中6个div赋给数组divs
            var divs = document.getElementById("divs").getElementsByTagName("div");
//            for循环遍历btns
            for(var i=0;i<btns.length;i++)
            {
                //得到当前btn在数组的的索引号
                btns[i].index = i;  // 难点
                btns[i].onclick = function(){
                    //让所有的 btn 类名清空
                    //alert(this.index);
                    for(var j=0;j<btns.length;j++)
                    {
                        btns[j].className = "";
                    }
                    // 当前的那个按钮 的添加 类名
                    this.className = "red";
                    //先隐藏所有的 div盒子
                    for(var i=0;i<divs.length;i++)
                    {
                        divs[i].style.display = "none";
                    }
                    // 留下与按钮相对应的div,既当前按钮序号有关
                    divs[this.index].style.display ="block";
                }
            }
        }
    </script>
</head>
<body>
<div class="box">
    <div class="top">
        <button>第一个</button>
        <button>第二个</button>
        <button>第三个</button>
        <button>第四个</button>
        <button>第五个</button>
    </div>
    <div class="bottom" id="divs">
        <div style="display: block;">盒子1</div>
        <div>盒子2</div>
        <div>盒子3</div>
        <div>盒子4</div>
        <div>盒子5</div>
    </div>
</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/luckybuling/article/details/81676140
今日推荐