JavaScript获取内联样式

这篇博客介绍了如何使用JavaScript来设置和获取DOM元素的样式。通过元素的style属性,可以方便地改变元素的宽高和背景色。同时强调了当样式中存在!important时,JS无法覆盖该样式。还提醒注意,style属性只能获取内联样式,不包括CSS文件中的样式。
摘要由CSDN通过智能技术生成
<!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>案例031</title>
                  <style>
                                    #box1{
                                                      width: 200px;
                                                      height: 200px;
                                                      background-color: rgb(162, 0, 255);
                                    }
                  </style>
                  <script>
                                    window.onload = function(){
                                                      var btn01 = document.getElementById("btn01");
                                                      var box1 = document.getElementById("box1");
                                                      btn01.onclick = function(){
                                                                        box1.style.width = "300px";
                                                                        box1.style.height = "300px";
                                                                        box1.style.backgroundColor = "yellow";
                                                      }
                                                      var btn02 = document.getElementById("btn02");
                                                      btn02.onclick = function(){
                                                                        console.log(box1.style.width);
                                                                        console.log(box1.style.height);
                                                                        console.log(box1.style.backgroundColor);
                                                      }

                                    }
                  </script>
</head>
<body>
          <button id="btn01">设置元素的样式</button> 
          <button id="btn02">获取元素的样式</button> 
          <br></br>
          <div id="box1"></div>       
</body>
</html>
      我们现在获取元素样式以及设置元素样式都可以通过style属性获取,如果要设置样式的话,元素.style.属性 = "属性值",如果是获取样式的话,就是这样元素.style.属性,具体的实例就是上面代码。
      其中注意的是,样式中写了!important,则此时样式会有最高的优先级,即使通过JS也不能覆盖该样式,此时将会导致JS修改样式失效,所以尽量不要为样式添加!important。style样式只能获取内联样式,不能获取在CSS选择器里面的。因为JavaScript通过style设置的样式是内联样式。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值