Home >Web Front-end >JS Tutorial >How to Get an HTML Element's Style Values Across Different Browsers?

How to Get an HTML Element's Style Values Across Different Browsers?

DDD
DDDOriginal
2024-12-01 07:19:14922browse

How to Get an HTML Element's Style Values Across Different Browsers?

How to Retrieve an HTML Element's Style Values in JavaScript

Retrieving style values from HTML elements is essential for manipulating elements' appearance dynamically. While setting styles using JavaScript is straightforward, accessing styles defined in style tags can be tricky.

Cross-Browser Considerations

Accessing element styles requires a cross-browser approach. Internet Explorer uses its own property, currentStyle, while other browsers follow the W3C standard and utilize document.defaultView.getComputedStyle.

Custom Cross-Browser Function

To handle cross-browser inconsistencies, a custom function is often employed:

function getStyle(el, styleProp) {
  var value, defaultView = (el.ownerDocument || document).defaultView;
  // W3C standard way:
  if (defaultView && defaultView.getComputedStyle) {
    // sanitize property name to css notation
    styleProp = styleProp.replace(/([A-Z])/g, "-").toLowerCase();
    return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
  } else if (el.currentStyle) { // IE
    // sanitize property name to camelCase
    styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
      return letter.toUpperCase();
    });
    value = el.currentStyle[styleProp];
    // convert other units to pixels on IE
    if (/^\d+(em|pt|%|ex)?$/i.test(value)) { 
      return (function(value) {
        var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
        el.runtimeStyle.left = el.currentStyle.left;
        el.style.left = value || 0;
        value = el.style.pixelLeft + "px";
        el.style.left = oldLeft;
        el.runtimeStyle.left = oldRsLeft;
        return value;
      })(value);
    }
    return value;
  }
}

Usage

To retrieve the style property of an element:

var element = document.getElementById("box");
var width = getStyle(element, "width");

Current Considerations

The above function may not handle all edge cases, particularly for colors where the returned value may differ between IE and other browsers.

The above is the detailed content of How to Get an HTML Element's Style Values Across Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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