javascript - trick to get and set CSS style

while it will not be so much trouble if not for IE; most of the browers will use the attribute style,and you can set string to the via get/setAttribute("style"), but it does not work for ie, ie has a property of style object.  but it provide another atribute elem.style.cssText;

 

below shows the code that you can use to set the style . 

 

 

 

<html>
<head>
<title>Style Attribute Test</title>
<script type="text/javascript">
  /**
  *@Name: isXML
  *@Comment: tell if an element is an xml or an html
  */
  function isXML(elem) {
    return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML";
  }

(function () {
  // Create a dummy div to test access the style information
  var div = document.createElement("div");
  div.innerHTML = '<b style="color:red;"></b>';
  // Get the style information from getAttribute
  // (IE uses .cssText insted)
  var hasStyle = /red/.test(div.firstChild.getAttribute("style"));
  this.styleAttr = function (elem, value) {
    var hasValue = typeof value !== "undefined";
    // Use the isXML method from Listing 12-3
    if (!hasStyle && !isXML(elem)) {
      alert("you are there");
      if (hasValue) {
        elem.style.cssText = value + "";
      }
      return elem.style.cssText;
    } else {
      if (hasValue) {
        elem.setAttribute("style", value);
      }
      return elem.getAttribute("style");
    }
  };
})();
window.onload = function(){
  var a = document.getElementById("a");
  // Fails in Internet Explorer
  //alert(a.getAttribute("style"));
  // Alerts out "color:red;"
  alert(styleAttr(a));
};
</script>
</head>
<body>
  <a id="a" href="/" style="color:red;"></a>
</body>
</html>

你可能感兴趣的:(JavaScript)