style属性的获取和修改
在DOM当中,如果想设置样式,有两种形式:
-
className(针对内嵌样式)
-
style(针对行内样式)
这篇文章,我们就来讲一下style。
需要注意的是:style是一个对象,只能获取行内样式,不能获取内嵌的样式和外链的样式。例如:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { border: 6px solid red; } </style> </head> <body> <div class="box1" style="width: 200px;height: 100px;background-color: pink;"></div> <script> var box1 = document.getElementsByTagName("div")[0]; console.log(box1.style.backgroundColor); console.log(box1.style.border); //没有打印结果,因为这个属性不是行内样式 console.log(typeof box1.style); //因为是对象,所以打印结果是Object console.log(box1.style); //打印结果是对象 </script> </body> </html>
打印结果:
上图显示,因为border属性不是行内样式,所以无法通过style对象获取。
通过 js 读取元素的样式
语法:(方式一)
元素.style.样式名
备注:我们通过style属性读取的样式都是行内样式。
语法:(方式二)
元素.style["属性"]; //格式 box.style["width"]; //举例
方式二最大的优点是:可以给属性传递参数。
通过 js 设置元素的样式
语法:
元素.style.样式名 = 样式值;
举例:
box1.style.width = "300px"; box1.style.backgroundColor = "red"; // 驼峰命名法
备注:我们通过style属性设置的样式都是行内样式,而行内样式有较高的优先级。但是如果在样式中的其他地方写了!important
,则此时!important
会有更高的优先级。
style属性的注意事项
style属性需要注意以下几点:
(1)样式少的时候使用。
(2)style是对象。我们在上方已经打印出来,typeof的结果是Object。
(3)值是字符串,没有设置值是“”。
(4)命名规则,驼峰命名。
(5)只能获取行内样式,和内嵌和外链无关。
(6)box.style.cssText = “字符串形式的样式”。
cssText
这个属性,其实就是把行内样式里面的值当做字符串来对待。在上方代码的基础之上,举例:
<script> var box1 = document.getElementsByTagName("