β

Get Pseudo-Element Properties with JavaScript

David Walsh Blog 280 阅读

CSS pseudo-elements are incredibly useful — they allow us to create CSS triangles for tooltips and perform a number of other simple tasks while preventing the need for additional HTML elements.  To this point, these pseudo-element CSS properties have been unreachable by JavaScript but now there’s a method for getting them!

Assume your CSS looks like:

.element:before {
	content: 'NEW';
	color: rgb(255, 0, 0);
}

To retrieve the color property of the .element:before, you could use the following JavaScript:

var color = window.getComputedStyle(
	document.querySelector('.element'), ':before'
).getPropertyValue('color')

Passing the pseudo-element as the second argument to window.getComputedStyle allows access to said pseudo-element styles!  Keep this snippet in your toolbox for years to come — pseudo-elements will only grow more useful with broader browser support!

Read the full article at: Get Pseudo-Element Properties with JavaScript

Treehouse

Crazy Egg

作者:David Walsh Blog
JavaScript, HTML5, AJAX, PHP, CSS, and ∞.
原文地址:Get Pseudo-Element Properties with JavaScript, 感谢原作者分享。

发表评论