获取元素的样式属性

以获取背景颜色为例

html部分

<div id="test">abcd</div>

css部分

#test {
    background-color: rgba(255, 0, 0, 0.5);
}

JS部分

var testDom = document.getElementById('test');
console.log(testDom.ownerDocument.defaultView.getComputedStyle(testDom,null).backgroundColor);

DOM.style只能获取内联的样式,所以通过上面的方法,可以读取到元素样式属性的值。

相应的API,window.getComputedStyle()

原文地址:https://www.cnblogs.com/xiaoyucoding/p/5818490.html