Javascript获取CSS伪元素属性的实现代码
CSS伪元素非常强大,它经常被用来创建CSS三角形提示,使用CSS伪元素可以实现一些简单的效果但又不需要增加额外的HTML标签。有一点就是Javascript无法获取到这些CSS属性值,但现在有一种方法可以获取到:
看看下面的CSS代码:
.element:before{ content:'NEW'; color:rgb(255,0,0); }.element:before{ content:'NEW'; color:rgb(255,0,0); }
为了获取到.element:before的颜色属性,你可以使用下面的代码:
varcolor=window.getComputedStyle( document.querySelector('.element'),':before' ).getPropertyValue('color')varcolor=window.getComputedStyle( document.querySelector('.element'),':before' ).getPropertyValue('color')
把伪元素作为第二个参数传到window.getComputedStyle方法中就可以获取到它的CSS属性了。把这段代码放到你的工具函数集里面去吧。随着伪元素被越来越多的浏览器支持,这个方法会很有用的。
译者注:window.getComputedStyle方法在IE9以下的浏览器不支持,getPropertyValue必须配合getComputedStyle方法一起使用。IE支持CurrentStyle属性,但还是无法获取伪元素的属性。
准确获取指定元素CSS属性值的方法。
<scripttype="text/javascript"> functiongetStyle(elem,name) { //如果该属性存在于style[]中,则它最近被设置过(且就是当前的) if(elem.style[name]) { returnelem.style[name]; } //否则,尝试IE的方式 elseif(elem.currentStyle) { returnelem.currentStyle[name]; } //或者W3C的方法,如果存在的话 elseif(document.defaultView&&document.defaultView.getComputedStyle) { //它使用传统的"text-Align"风格的规则书写方式,而不是"textAlign" name=name.replace(/([A-Z])/g,"-$1"); name=name.toLowerCase(); //获取style对象并取得属性的值(如果存在的话) vars=document.defaultView.getComputedStyle(elem,""); returns&&s.getPropertyValue(name); //否则,就是在使用其它的浏览器 } else { returnnull; } } </script>