style属性的设置和获取
在DOM当中,如果想设置样式,有两种形式:
className(针对内嵌样式表)
style(针对行内样式)
这一段就来讲一下style。
需要注意的是:style是一个对象,只能获取行内样式,不能获取内嵌的样式和外链的样式。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <!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); console.log(box1.style); </script> </body> </html>
|
打印结果:

上图显示,因为border属性不是行内样式,所以无法通过style对象获取。
style属性的注意事项
style属性需要注意以下几点:
(1)样式少的时候使用。
(2)style是对象。
我们在上方已经打印出来,typeof的结果是Object。
(3)值是字符串,没有设置值是“”。
(4)命名规则,驼峰命名。和css不一样。
(5)只能获取行内样式,和内嵌和外链无关。
本段最开始的时候讲到的。
- (6)box.style.cssText = “字符串形式的样式”。
cssText这个属性,其实就是把行内样式里面的值当做字符串来对待。在上方代码的基础之上,举