<button class="stately" id="stately" value="1" onclick="updateFlag(this);">牢固</button>class="stately"   这个stately里面有个属性color现在我如何通过他这个名字去拿到他对应属性的这个color值呢?

解决方案 »

  1.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <style>
    body{ font-size:14px}
    </style>
    </head>
    <body>
    <script type="text/javascript">
    function getStyle( elem, name ) 

    //如果该属性存在于style[]中,则它最近被设置过(且就是当前的) 
      if (elem.style[name]) 
      { 
        return elem.style[name]; 
      } 
    //否则,尝试IE的方式 
      else if (elem.currentStyle) 
      { 
        return elem.currentStyle[name]; 
      } 
    //或者W3C的方法,如果存在的话 
       else if (document.defaultView && document.defaultView.getComputedStyle) 
      { 
        //它使用传统的"text-Align"风格的规则书写方式,而不是"textAlign" 
       name = name.replace(/([A-Z])/g,"-$1"); 
       name = name.toLowerCase(); 
       //获取style对象并取得属性的值(如果存在的话) 
       var s = document.defaultView.getComputedStyle(elem,""); 
       return s && s.getPropertyValue(name); 
       //否则,就是在使用其它的浏览器 

    else 
      { 
        return null; 
      } 
    }alert(getStyle(document.body,'fontSize'))
    </script>
    </body>
    </html>
      

  2.   

    <script>
    window.onload=function(){
        var o=document.getElementById("aa");
        var color=window.getComputedStyle?window.getComputedStyle(o,null).color:o.currentStyle["color"];
        alert(color)
    }
    </script>
    <style type="text/css">
    .test{color:red}
    </style>
    <div id="aa" class="test"></div>
    需要注意的是,在非IE标准浏览器中,返回的是rgb格式的。
    以上面的例子来说,定义的color:red
    在IE中获取到的值:red
    在其他标准浏览器中获取到的值:rgb(255, 0, 0)且此方法只能用来获取值,要设置属性还是得使用 对象.style.属性=值