关于JS动态修改CSS样式问题(class和style) - wkyseo/blog GitHub Wiki

有时我们需要动态生成效果,那么就需要对页面的css进行各种处理,进而达到一些样式的改变。如动画,拖放等效果。所以使用JS正确的来对页面样式修改是灰常重要的。

修改标签的class属性值

直接在css中定义多种css类型 然后在事件中对DOM对象的class属性进行切换,是最简单可行的一种方式。也是目前使用最多的方法。此方法会覆盖对象原有的class属性

<script type="text/javascript"> var obj = document.getElementById("div"); obj.className = "otherclass"; </script>

非标准ECMAScript来进行修改其class的值。

还有就是使用ES标准来进行修改,就是使用DOM的setAttribute方法。但是他有一个兼容性问题。

    <script type="text/javascript">
      var obj = document.getElementById("div");
      obj.setAttribute("className","otherclass");//IE下使用className
      obj.setAttribute("class","otherclass");//FF下的方式 所以要注意
    </script>

setAttribute()对id同样适用。

##添加行内样式 直接使用 dom_obj.style.*** = "***"; 来进行对其样式的覆盖。由于行内样式优先级最高,所以能覆盖其他节点的样式。 该方法也是极为常用的,唯一需要注意的就是对于样式名的大小写问题。如:border-left 应该为 borderLeft 。

使用该方法我们可能需要用到计算当前样式值的方法。这里也具有兼容性问题。currentStyle只有IE支持。取得当前应用的样getComputedStyle支持FF,Opera,Safari,Chrome等浏览器。取得最终应用的样式。

<script type="text/javascript">

    var obj = document.getElementById("div");

    objh=document.defaultView.getComputedStyle(obj,null).height;

    //或者
    objh=window.getComputedStyle(obj,null)[height];

    //IE下 需要
    objh=obj.currentStyle[height];

</script>

解决兼容性的方法

function getStyle(element,property) {

      var value = element.style[camelize(property)];

      if(!value) {

        if(document.defaultView && document.defaultView.getComputedStyle) {

          value = document.defaultView.getComputedStyle(element).getPropertyValue(property);

        } else if(element.currentStyle) {

          value = element.currentStyle[camelize(property)];

         }

      } 
  
      return value;
    }
⚠️ **GitHub.com Fallback** ⚠️