Javascript gets the implementation code for CSS pseudo element attributes

  • 2020-03-30 04:03:27
  • OfStack

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 adding extra HTML tags. One thing is that Javascript can't get these CSS property values, but now there's a way to get them:

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);
}

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')

Method to get the exact CSS attribute value of the specified element.


<script type="text/javascript"> 
function getStyle( elem, name ) 
{ 
  //If the property exists in style[], it was recently set (and is currently)
  if (elem.style[name]) 
  { 
    return elem.style[name]; 
  } 
  //Otherwise, try the IE approach
  else if (elem.currentStyle) 
  { 
    return elem.currentStyle[name]; 
  } 
  //Or the W3C approach, if one exists
  else if (document.defaultView && document.defaultView.getComputedStyle) 
  { 
    //It USES the traditional "text-align" style of rule writing instead of "textAlign"
    name = name.replace(/([A-Z])/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, you are using another browser
  } 
  else 
  { 
    return null; 
  } 
} 
</script>

Related articles: