zoukankan      html  css  js  c++  java
  • js操作元素样式

    一,内嵌样式:

     1 <div id ="myDiv" style="100px;height:100px;background-color:red; border:1px solid black;"></div>
     2 <script>
     3     var myDiv = document.getElementById("myDiv");
     4 
     5     alert(myDiv.style.width);//100px
     6 
     7     alert(myDiv.style['height']);//100px
     8 
     9     var style=myDiv.style;
    10     alert(style.backgroundColor);//red
    11 
    12     myDiv.style.backgroundColor='green';//myDiv背景色变为绿色 
    13 </script>

     此时style属性可以操作,可以通过 ele.style.arr  方式获取并修改样式。

    注意:1 当获取类似font-size 属性时,为避免混淆javascript保留字符  - ,需要转化为驼峰命名法,改为fontSize;

       2.属性值放在双引号中。

    二,放在<style></style>中的和外部样式表:

     1 <style type="text/css">
     2 #myDiv {
     3     background-color:blue;
     4     width:100px;
     5     height:200px;
     6 }
     7 </style>
     8 
     9 <div id ="myDiv" style="background-color:red; border:1px solid black;"></div>
    10 <script>
    11     var myDiv = document.getElementById("myDiv");
    12     var finalStyle = myDiv.currentStyle ? myDiv.currentStyle : document.defaultView.getComputedStyle(myDiv, null);/*利用判断是否支持currentStyle(是否为ie)
    13     来通过不同方法获取style*/
    14     alert(finalStyle.backgroundColor);    //"red"
    15     alert(finalStyle.width);              //"100px"
    16     alert(finalStyle.height);             //"200px"
    17 </script>

       由于表现层与结构层的分离,使用style属性会无效,对于这种情况,不同浏览器的方法不一样。

    1   非ie浏览器中,使用document.defaultView对象的getComputedStyle(ele,null/伪类)方法,该方法接受两个参数,第一个为要考察的元素,第二个则要根据情况,如果只是考察元素本身则为null,如果要 考察伪类,则为响应的伪类。该方法获取到的为元素应用的最终样式组合,同样是类似数组的一个实例。

    2   在ie浏览器中,对getComputedStyle()方法不支持,但是针对每个标签元素都有一个近似于style属性的currentStyle的属性,且用法和style用法相同。只不过获取到的样式范围不一样。currenStyle获取到的和getComputedStyle()方法相接近。

    为了在处理时达到兼容,可以根据这两种不同的处理方式创建一个函数来达到兼容目的,使得不管在那种浏览器中,都可以成功获取样式。如上图所示。

  • 相关阅读:
    HDU1879 kruscal 继续畅通工程
    poj1094 拓扑 Sorting It All Out
    (转)搞ACM的你伤不起
    (转)女生应该找一个玩ACM的男生
    poj3259 bellman——ford Wormholes解绝负权问题
    poj2253 最短路 floyd Frogger
    Leetcode 42. Trapping Rain Water
    Leetcode 41. First Missing Positive
    Leetcode 4. Median of Two Sorted Arrays(二分)
    Codeforces:Good Bye 2018(题解)
  • 原文地址:https://www.cnblogs.com/younylight/p/7661956.html
Copyright © 2011-2022 走看看