最近别人问了我一下getComputedStyle的封装过程为什么要写if(currentStyle),我当时也没反应过来,毕竟好长时间没有用了,因此决定来探究一下这个getComputedStyle()函数,即是温习也是和大家分享,如果有不对的地方欢迎在评论区批评指正;
首先,回到问题开始,getComputedStyle和currentStyle都是用来获取样式的,只能获取样式而不能修改样式,在修改样式的时候需要用到style,eg:obj.color=“red”;其次,在获取样式方面,支持二者的浏览器不同,currentStyle对应的是IE系列,getComputedStyle则是其他的四大浏览器(Chrome、FireFox、Opera、Safari)支持的(至少我这里的Chrome浏览器对getCurrentStyle不兼容),这也许就是封装函数的由来了。
为了方便大家上机调试,验证下面结论,下面先给出代码,
如果想看结论,请点我,直接跳过代码:
CSS代码如下:
<style>
#mydiv {
position: relative;
width: 150px;
height: 150px;
background-color: #facbf4;
box-sizing: border-box;
/*这里启用CSS3的盒子模型*/
font-size: 12px;
color: #b78bdb;
margin: 200px auto;
padding: 20px;
}
#mydiv:before {
position: absolute;
top: 0px;
left: 0px;
content: "";
/*不加content:"" Chrome浏览器会显示不出来*/
width: 20px;
height: 10px;
display: block;
border-left: 1px red solid;
border-top: 1px red solid;
}
#mydiv:after {
position: absolute;
right: 0px;
bottom: 0px;
content: "";
/*不加content:"" Chrome浏览器会显示不出来*/
width: 20px;
height: 10px;
display: block;
border-right: 1px red solid;
border-bottom: 1px red solid;
}
</style>
js代码如下:
<script>
var mydiv = document.getElementById("mydiv");
console.log(getComputedStyle(mydiv).color); //只能获取,不能修改,如果要修改需要使用style来修改
console.log("currentStyle:", mydiv.currentStyle["color"]);
console.log("currentStyle:", mydiv.currentStyle.color);
console.log("下面探究getComputedStyle与currentStyle对伪类的支持情况:");
//为了方面说明问题,就直接取了右边框,直接border的话,遵循上右下左的显示规则,是三原色直接返回string,否则返回rgb值
console.log("getComputedStyle对伪类的支持情况:" + getComputedStyle(mydiv, "after").borderRightColor);
console.log("currentStyle对伪类的支持情况:" + currentStyle(mydiv, "after").borderRightColor);
</script>
问题一:浏览器对getComputedStyle和currentStyle的兼容性验证:
站在Chrome浏览器的角度分析:
站在ie浏览器的角度:
结论一:Chrome浏览器不支持currentStyle,ie系列浏览器中,ie5-ie8使用的是自己独创的currentStyle,不支持getComputedStyle,而在后期的ie9以及ie9+浏览器中直接兼容了二者;
细心的同学们会发现这里的盒子有个边框,这个写法其实是用伪类加上绝对定位做出来的,挺简单的(方法来源:bilibili pink老师,echarts入门到数据可视化实战),伪类在当前用的还是挺多的,除了这个还有,iconfont图标字体等的使用。接下来探究二者对伪类的支持性。
问题二:getComputedStyle和currentStyle对伪类的兼容性验证:
站在getcomputedStyle的角度:
站在currentStyle的角度:
结论二:currentStyle不支持伪类,getComputedStyle支持伪类;并且,getComputedStyle的第二个参数就是伪类,“before”,“after”,“null”(默认值,或者"false"),可以说这样设置,我们对伪类的操控力又增强了。
解释:为什么我有点胡扯一堆,直接指出参数和结论它不香吗,还要去比较二者,加上验证。其实我也是想自己操作一下,毕竟,实践是检验真理的唯一标准嘛。在当前,有了jQuery,CSS的处理已经被兼容的差不多了,甚至有更多比jQuery更好的插件,如果你也想了解这个getComputedStyle的第二个参数,那么说明你也可能希望了解一下这些,因此我才“胡乱取名”。
本片博文到此结束啦,谢谢阅读!