获取元素计算后样式
前面提到的使用元素.style.属性名
可以获取样式,但是该方式只能获取行内样式。所以为了解决这个局限性,浏览器提供了window.getComputedStyle()
方法,用来获取元素样式,因为元素样式都是经过浏览器计算后才渲染的,所以可以说是获取元素计算后样式。
看下面例子:
先给div一个行内样式和一个内部样式,绑定元素:
<style>
div{
color: tomato;
background-color: red;
}
</style>
<div id="box" class="box" style="width: 100px; height: 100px;"></div>
<script>
var box = document.getElementById("box");
</script>
使用元素.style.属性名
方式,只能获取行内样式:
console.log(box.style.width); // 100px
console.log(box.style.color); // 空的,获取不到
console.log(box.style.backgroundColor); // 空的,获取不到
使用window.getComputedStyle()
方法,参数是要获取的元素,即要获取哪个元素的样式,参数就是哪个元素:
var cssObj = window.getComputedStyle(box);
console.log(cssObj.width); // 100px
console.log(cssObj.color); // rgb(255, 99, 71)
console.log(cssObj.backgroundColor); // rgb(255, 0, 0)
window.getComputedStyle()
方法具有兼容性问题,在IE浏览器里面不支持window.getComputedStyle()
方法,所以IE浏览器提供了另一种方式,使用currentStyle属性
,但是该属性在其他浏览器不支持
在IE浏览器中使用currentStyle属性
获取元素计算后样式:
var curStyle = box.currentStyle;
console.log(curStyle.width); // 100px
console.log(curStyle.color); // rgb(255, 99, 71)
console.log(curStyle.backgroundColor); // rgb(255, 0, 0)
封装函数来解决上述兼容性问题
// 封装函数解决上面的兼容性问题
function getCss(dom, attr){
// 如果能够使用window.getComputedStyle()方法,则执行if里面的代码
if(window.getComputedStyle){
// 获取这个元素的所有样式组成的对象
var cssObj = getComputedStyle(dom);
// 把需要的属性返回
return cssObj[attr];
}else{
// 如果不能使用window.getComputedStyle()方法,就使用currentStyle属性
var curStyle = dom.currentStyle;
// 把需要的属性返回
return curStyle[attr];
}
}
var width = getCss(box, "width");
console.log(width); // 100px
var color = getCss(box, "color");
console.log(color); // rgb(255, 99, 71)
var bgColor = getCss(box, "backgroundColor");
console.log(bgColor); // rgb(255, 0, 0)
调用上述函数,可以解决浏览器不兼容问题。
将函数封装在一个外部js文件中
有时候为了方便调用,我们可以将函数封装到一个外部js文件中,是需要引用即可。为了减少变量名的占用,所以在外部js中将全部的函数放在一个对象里面。
用法:
- 创建外部js文件getCss.js
var GETCSS = {
getCss:function(dom, attr){
// 如果能够使用window.getComputedStyle()方法,则执行if里面的代码
if(window.getComputedStyle){
// 获取这个元素的所有样式组成的对象
var cssObj = getComputedStyle(dom);
// 把需要的属性返回
return cssObj[attr];
}else{
// 如果不能使用window.getComputedStyle()方法,就使用currentStyle属性
var curStyle = dom.currentStyle;
return curStyle[attr];
}
}
}
- 将js引入
<script src="../js/getCss.js"></script>
- 调用js中的GETCSS对象里面的函数,GETCSS.getCss(),参数1是元素,参数2是元素的属性名
var W = GETCSS.getCss(box, "width");
var C = GETCSS.getCss(box, "color");
var BGC = GETCSS.getCss(box, "backgroundColor");
console.log(W); // 100px
console.log(C); // rgb(255, 99, 71)
console.log(BGC); // rgb(255, 0, 0)