控制div属性

<!DOCTYPE html>
<html>
    <head>
        <title>控制div属性</title>
        <style type="text/css">
            *{ margin: 0px; padding: 0px; }
            #app1{ width: 300px; height: 160px; margin: 0 auto; }
            #app1 .btng button{ width: 38px; height: 20px; outline: none; }
            .btng{ width: 210px; height: 20px; margin: 10px auto; }
            #bgcolor{ width: 100px; height: 100px; background: black; margin: 20px auto; }
        </style>
    </head>
    <body>
        <div id="app1">
            <div class="btng">
                <button>变宽</button>
                <button>变高</button>
                <button>变色</button>
                <button>隐藏</button>
                <button>重置</button>
            </div>
            <p id="bgcolor"></p>
        </div>

        <script type="text/javascript">
            // 改变样式函数
            var changeStyle = function (elem, attr, value)
                {
                    elem.style[attr] = value;
                };
            window.onload = function(){
                // 获取元素
                var btngcount = document.getElementsByTagName("button");
                var bgcolor = document.getElementById("bgcolor");
                // 储存要更改的元素属性
                var btnAtt = ["width","height","background","display","display"];
                // 储存要更改的值
                var btnVal = ["200px","200px","red","none","block"];
                // 遍历元素
                for(var i = 0; i < btngcount.length; i++){
                    // 令按钮的下标等于i
                    btngcount[i].index = i;
                    // 点击事件
                    btngcount[i].onclick = function(){
                        // 先将样式清空
                        bgcolor.style.cssText = "";
                        // this.index == oBtn.length - 1 && (oDiv.style.cssText = "");
                        changeStyle(bgcolor, btnAtt[this.index], btnVal[this.index]);
                    }
                }
            }
        </script>
    </body>
</html>

                                                      效果图:

                                                           

猜你喜欢

转载自blog.csdn.net/qq_44254672/article/details/90483071