在ie下使用obj.style.marginRight可以正确得到auto的属性,在firefox或chrome下得到的却是数字,如何能正确得到auto属性呢?使用obj.currentStyle或window.getComputedStyle得到的也是数字。

解决方案 »

  1.   

    看不懂?<html>
    <head>
    <title></title>
    <script>
    function getObjStyle(obj, style)
    {
    if(obj.currentStyle)
    return obj.currentStyle[style];
    else if(window.getComputedStyle)
    return window.getComputedStyle(obj, null)[style];
    else
    return null;
    }
    </script>
    <style>
    #test{margin-right: auto; margin-left: auto; border: #a0a0a0 1px solid; width: 800px; height: 80px;}
    </style>
    </head>
    <div id="test" onclick="alert(getObjStyle(this, 'marginRight'))">test</div>
    </html>
    我这里显示:311px
      

  2.   

    直接用 .style 你那个方法是获得的计算后的margin
      

  3.   

    直接用 .style是不能获得<head>标签内的属性的,只能获得当前块内的属性
    <div style="margin-left: auto;" onclick="alert(this.style.marginLeft)">test</div>这里alert是auto<html>
    <head>
    <title></title>
    <style>
    #test{margin-right: auto; margin-left: auto; border: #a0a0a0 1px solid; width: 800px; height: 80px;}
    </style>
    </head>
    <div id="test" onclick="alert(this.style.marginLeft)">test</div>
    </html>这里alert是空的