javascript - trick to get and set CSS style

本文介绍了如何在不同浏览器中设置样式属性,并着重解决了IE浏览器使用`style`属性时遇到的问题,提供了设置样式的方法和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值