javascript-计算元素的所有样式
在日常开发中,如果你需要读取html元素的style样式或class样式的属性值时,就可以使用DOM2级样式中新增的方法-getComputedStyle()。
getComputedStyle()
getComputedStyle()方法是window对象的方法,可以通过window.getComputedStyle(),或者document.defaultView.getComputedStyle()方法调用。而document.defaultView的返回值就是window。
接收2个参数:
- 需要计算样式的元素,必须
- 伪元素字符串(’:after’),非必须
示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>计算样式</title>
<style>
#content{
width: 300px;
height: 200px;
background-color: darkgrey;
}
</style>
</head>
<body>
<div id="content" style="background-color: darkmagenta;">
内容区域
</div>
<script>
var content = document.querySelector('#content')
var computedStyle = document.defaultView.getComputedStyle(content, null)
var html = ''
function getComputedStyleValue(computedStyle, property){
return property + ': ' + computedStyle[property] + ';'
}
html = '<span>'+getComputedStyleValue(computedStyle, 'background-color')+'</span><br/>'+
'<span>'+getComputedStyleValue(computedStyle, 'width')+'</span><br/>' +
'<span>'+getComputedStyleValue(computedStyle, 'height')+'</span><br/>'
content.innerHTML = html
</script>
</body>
</html>
如上图所示:
浏览器通过getComputedStyle()方法读取样式,这些样式是可读的,也包括所有的默认样式。background-color被替换了,且浏览器将颜色转成rgb格式,经测试,IE10/11,Chrome等5大主流浏览器都支持该方法。
兼容IE8
var content = document.querySelector('#content')
var computedStyle = getConstantStyle(content, null)
var html = ''
function getComputedStyleValue(computedStyle, property){
return property + ': ' + computedStyle[property] + ';'
}
// 获取计算样式
function getConstantStyle(el, pelStr){
var w = document.defaultView
if (w && w.getComputedStyle) {
return document.defaultView.getComputedStyle(el, pelStr)
} else {
return el.currentStyle
}
}
html = '<span>'+getComputedStyleValue(computedStyle, 'background-color')+'</span><br/>'+
'<span>'+getComputedStyleValue(computedStyle, 'width')+'</span><br/>' +
'<span>'+getComputedStyleValue(computedStyle, 'height')+'</span><br/>'
content.innerHTML = html
IE8会显示该颜色的原始名称,即:darkmagenta
小结
- 通过getComputedStyle()可以获取元素的所有样式属性
- 计算样式属性都是只读的,不能设置