Home > Web Front-end > CSS Tutorial > How Can I Get the Exact CSS Property Value (Including Units) of an Element in JavaScript?

How Can I Get the Exact CSS Property Value (Including Units) of an Element in JavaScript?

Mary-Kate Olsen
Release: 2024-12-11 09:10:20
Original
531 people have browsed it

How Can I Get the Exact CSS Property Value (Including Units) of an Element in JavaScript?

Get Element CSS Property Value as Set (Percent/Em/Px)

Obtaining the CSS property value of an element as specified in the style rules can be challenging, especially when the property has been set in various units. In Google Chrome, the getComputedStyle() method and jQuery's css() method both return the current value in pixels.

Solution: getMatchedStyle Function

To address this issue, a JavaScript function called getMatchedStyle() was developed. It takes an element and a property as arguments and returns the value as it was set in the CSS rules.

function getMatchedStyle(elem, property) {
  // Check element's own style first
  var val = elem.style.getPropertyValue(property);
  if (elem.style.getPropertyPriority(property)) return val;

  // Get matched CSS rules
  var rules = getMatchedCSSRules(elem);

  // Iterate rules in reverse order of priority
  for (var i = rules.length; i--;) {
    var r = rules[i];
    var important = r.style.getPropertyPriority(property);

    // Reset value if important or not yet set
    if (val == null || important) {
      val = r.style.getPropertyValue(property);
      if (important) break;
    }
  }

  return val;
}
Copy after login

Example

Consider the following HTML code with CSS rules:

<div class="b">div 1</div>
<div>
Copy after login

The following JavaScript code uses getMatchedStyle() to obtain the width values for the divs:

var d = document.querySelectorAll('div');

for (var i = 0; i < d.length; ++i) {
  console.log("div " + (i + 1) + ":  " + getMatchedStyle(d[i], 'width'));
}
Copy after login

Results:

div 1:  100px
div 2:  50%
div 3:  auto
div 4:  44em
Copy after login

The above is the detailed content of How Can I Get the Exact CSS Property Value (Including Units) of an Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template