• 使用DOM操作CSS


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            #box1{
                 200px;
                height: 200px;
                background-color: red ; 
                /*background-color: red !important;*/
            }
        </style>
        <script>
            window.onload=function(){
                
            /* 点击按钮以后,修改box1的大小 */
            // 获取box1
            var box1=document.getElementById("box1");
            //为按钮绑定单击响应函数
            var btn01=document.getElementById("btn01");
            btn01.onclick=function(){
                // alert("hello");//测试
    
                /* 修改box1的宽度
                    通过js修改元素的样式
                    语法:元素.style.样式名=样式值
    
                    注意:如果CSS的样式名中含有-
                        这种名称在js中是不合法的比如background-color
                        需要将这种样式名修改为驼峰命名法
                        去掉-,然后将-后的字母大写
    
                    我们通过style属性设置的样式都是内联样式
                        而内联样式有较高的优先级,所以通过js修改的样式往往会立即显示
    
                    但是如果在样式中写了 !important,则此时样式会有最高的优先级,
                     即使通过js也不能覆盖该样式,此时将会导致js修改样式失效
                     所以尽量不要为样式添加 !important
    
                */
                box1.style.width="300px";
                box1.style.height="300px";
                box1.style.backgroundColor="yellow";
            }; 
               
            
            // 点击按钮2以后,读取元素的样式
            var btn02=document.getElementById("btn02");
            btn02.onclick=function(){
    
                // 读取box1的样式
                /* 
                语法:元素.style.样式名
    
                通过style属性设置和读取的都是内联样式
                无法读取样式表中的样式
                */
    
                alert(box1.style.width);//width用的是box1.style.width="300px";不能用样式表中的 #box1{ 200px;}
            }
            };
        </script>
    </head>
    <body>
        <button id="btn01">点我一下</button>
        <button id="btn02">点我一下</button>
        <!-- div#box1 自动补全-->
        <div id="box1"></div>
    </body>
    </html>
  • 相关阅读:
    如何将数组初始化为全0?
    什么是优先级队列(priority queue)?
    C语言中指针的指针是如何工作的?
    什么是队列(Queue)?
    理解*ptr++
    【Luogu】P4172水管局长(LCT)
    【Luogu】P4159迷路(矩阵优化)
    【Luogu】P3971Alice And Bob(贪心)
    【Luogu】P3211XOR和路径(高斯消元)
    【Luogu】P2445动物园(最大流)
  • 原文地址:https://www.cnblogs.com/hr-7/p/14139933.html
Copyright © 2020-2023  润新知