获取元素的css样式有三种方法
-
ele.style
返回CSSStyleDeclaration 类型的对象,只能获取内联样式,可读,可写 -
window.getComputedStyle(el,null)
返回CSSStyleDeclaration 类型的对象,可以获取内联,嵌入样式,外联样式,仅读 -
document.defaultView.getComputedStyle(el,null)
同window一样
获取样式
ele.style.backgroundColor
ele.style["background-color"]
ele.style.getPropertyValue('background-color')
window.getComputedStyle(el,null).backgroundColor
window.getComputedStyle(el,null)["background-color"]
window.getComputedStyle(el,null).getPropertyValue('background-color')
<style>
.main{
background-color: #f00;
}
</style>
<div class="main" id="main" style="color:#000">
内容
</div>
<button onclick="getStyle()">获取元素的样式</button>
<div id="show"></div>
<script>
function getStyle(){
var $main = document.querySelector('#main')
var $show = document.querySelector('#show')
var eleStyle = $main.style //返回CSSStyleDeclaration 类型的对象,只能获取内联样式,可读,可写
var eleCss = window.getComputedStyle($main,null)//返回CSSStyleDeclaration 类型的对象,可以获取内联,嵌入样式,外联样式,仅读
var eleCssView = document.defaultView.getComputedStyle($main,null);
console.log(document.defaultView === window) // true
console.log(eleStyle)
console.log(eleCss)
console.log(eleCssView)
console.log(eleStyle.backgroundColor) // undefined
console.log(eleStyle.getPropertyValue('background-color')) // undefined
console.log(eleStyle.getPropertyValue('color')) // rgb(0,0,0)
console.log(eleCss.backgroundColor) // rgb(255,0,0)
console.log(eleCss["background-color"]) // rgb(255,0,0)
console.log(eleCss.getPropertyValue('background-color'))// rgb(255,0,0)
console.log(eleStyle.width) // undefined
console.log(eleCss.width) // 100px
$show.innerHTML = eleStyle
}
</script>