CSS pseudo-elements are very powerful and are often used to create CSS triangle hints. Using CSS pseudo-elements can achieve some simple effects without the need to add additional HTML tags. One thing is that Javascript cannot get these CSS attribute values, but now there is a way to get:
Take a look at the following CSS code:
.element:before { content: 'NEW'; color: rgb(255, 0, 0);}.element:before {content: 'NEW';color: rgb(255, 0, 0);}In order to get the color attribute of .element:before, you can use the following code:
var color = window.getComputedStyle( document.querySelector('.element'), ':before').getPropertyValue('color')var color = window.getComputedStyle(document.querySelector('.element'), ':before').getPropertyValue('color')Pass the pseudo-element as the second parameter to the window.getComputedStyle method to obtain its CSS attribute. Put this code into your tool function set. This method will be useful as pseudo-elements are supported by more and more browsers.
Translator's note: The window.getComputedStyle method is not supported in browsers below IE9, and getPropertyValue must be used with the getComputedStyle method. IE supports the CurrentStyle attribute, but it still cannot obtain the properties of the pseudo-element.
Method to accurately get the value of the CSS attribute of the specified element.
<script type="text/javascript"> function getStyle( elem, name ) { //If the property exists in style[], it has been recently set (and is the current one) if (elem.style[name]) { return elem.style[name]; } //Otherwise, try IE else if (elem.currentStyle) { return elem.currentStyle[name]; } //Or the W3C method, if it exists else if (document.defaultView && document.defaultView.getComputedStyle) { //It uses the traditional "text-Align" style regular writing method, rather than "textAlign" name = name.replace(/([AZ])/g,"-$1"); name = name.toLowerCase(); //Get the style object and get the value of the property (if it exists) var s = document.defaultView.getComputedStyle(elem,""); return s && s.getPropertyValue(name); //Otherwise, it is using another browser} else { return null; } } </script>