访问元素的样式
一、style
任何支持style特性的HTML元素在Javascript中都有一个对应的style属性。这个style对象是CSSStyleDeclaratioin的实例。包含着通过HTML的style特性指定的所有样式信息,不包含外部样式表和内嵌入样式表经层叠而来的样式。
在style特性中指定的任何CSS属性都将表现为这个style对象的相应属性。
对于使用短划线的CSS属性,要转换成驼峰大小写形式
css : background-color
javascript:e.style.backgroundColor
通过(style.属性名)取得的属性,可读可写!
let e = document.getElementsByClassName('demo')[0];
e.style.backgroundColor = 'yellow';
二、DOM样式属性和方法 (e.style的属性和方法)
<div class="demo" style="background-color:red"></div>
-------
let e = document.getElementByClassName('demo')[0];
1) cssText
e.style.cssText 能返回style特性中的CSS代码
e.style.cssText // "background-color:red"
2) length
e.style.length 返回应用给元素的css属性的数量
e.style.length // 1
3) item(index)
e.style.item 返回给定位置的css属性的名称。配合 length属性可以遍历style对象
4) getPropertyValue(propertyName)
返回给定的属性的字符串值
e.style.getPropertyValue('background-color') // red
5) setPropertyValue(propertyName,value,priority)
将给定属性设置为相应的值,并加上优先权标志(‘important’ | '')
e.style.setPropertyValue('border','1px solid black');
<div class="demo" style="background-color:red; border: 1px solid black"></div>
getComputedStyle()
document.defaultView.getComputedStyle() | window.getComputedStyle();
style对象只能提供支持style特性的任何元素的样式信息,对于外部和内嵌的或继承而来的元素的样式信息不支持。
document.getComputedStyle() 确能获取当前元素的所有最终使用的CSS属性值
getComputedStyle()有两个参数
①要取得计算样式的元素
②一个伪元素字符串(如':after')如果不需要,可以是null;
document.defaultView.getComputedStyle();
//当只写一个参数的话,就获取这个元素的样式信息。
//如果有二参数的话,就是获取这个元素的伪元素的样式信息。
这个方法是只读的!!!只读的!
IE的方法是e.currentStyle!