zoukankan      html  css  js  c++  java
  • [读码时间] 修改div元素属性值

    说明:代码是网上找的,注释由笔者添加!

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title>控制DIV属性</title>
        <style>
            #outer{
                width:500px;     /*外部div的宽度*/
                margin:0 auto;   /*上下外边距为0,左右外边距自动,即左右置中*/
                padding:0;        /*内边距为0*/
                text-align:center; /*文本置中*/
            }
            #div1{                
                width:100px;        /*长宽各100的正方形黑色方块*/
                height:100px;
                background:black;
                margin:10px auto;    /*左右置中,上下外边距10像素*/
                display:block;       /*显示设置为块元素*/
            }
        </style>
        <script>
            //此函数的作用是改变元素样式,接收3个参数,元素名,属性名,属性值
            var changeStyle = function (elem, attr, value) { 
                elem.style[attr] = value;
            };
            window.onload = function () {  //调用 onload,页面加载后就执行
                var oBtn = document.getElementsByTagName("input"); //获取所有的按钮,此命令返回一个Nodelist对象集
                var oDiv = document.getElementById("div1");   //获取div1元素的引用,此命令返回一个对象引用 
                var oAtt = ["width", "height", "background", "display", "display"];  //属性名数组
                var oVal = ["200px", "200px", "red", "none", "block"];  //属性值数组
    
                for (var i = 0; i < oBtn.length; i++) { //利用for循环给所有按钮注册click事件处理程序
                    oBtn[i].index = i;    //综合使用[]和.表示法,给每个按钮添加一个索引值
                    oBtn[i].onclick = function () {  //给每个按钮都注册单击click事件处理程序
    
                        this.index == oBtn.length - 1 && (oDiv.style.cssText = "");//这种写法很妙,this.index的值不变,0-4,不过我暂未完全理解它的妙处
    
                        changeStyle(oDiv, oAtt[this.index], oVal[this.index]);//调用changeStyle函数,改变样式
                    }
                }
            };
        </script>
    </head>
    <body>
        <div id="outer">                //一个div中包含5个按钮和1个div方块,按钮用来控制方法的各种样式改变
            <input type="button" value="变宽" />
            <input type="button" value="变高" />
            <input type="button" value="变色" />
            <input type="button" value="隐藏" />
            <input type="button" value="重置" />
            <div id="div1"></div>
        </div>
    </body>
    </html>
  • 相关阅读:
    yolo_to_onnx ValueError: need more tan 1 value to unpack
    yolo_to_onnx killed
    C++ 实现二维矩阵的加减乘等运算
    Leetcode 1013. Partition Array Into Three Parts With Equal Sum
    Leetcode 1014. Best Sightseeing Pair
    Leetcode 121. Best Time to Buy and Sell Stock
    Leetcode 219. Contains Duplicate II
    Leetcode 890. Find and Replace Pattern
    Leetcode 965. Univalued Binary Tree
    Leetcode 700. Search in a Binary Search Tree
  • 原文地址:https://www.cnblogs.com/sx00xs/p/6427094.html
Copyright © 2011-2022 走看看