2011-04-16 55 views
1

当我在样式表中设置属性时,我无法访问JavaScript函数中一个图像元素的left属性,但是当我在图像标签上使用内联样式时,它工作正常。为什么我无法在JavaScript函数中访问此CSS属性?

这里是我的代码:

<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head id="Head1" runat="server"> 
     <title></title> 
     <script type="text/javascript"> 
      function moveObjRight(obj) { 
       var a = document.getElementById(obj); 
       alert(a.style.left) 
      } 
     </script> 
     <style type="text/css"> 
      #AS 
      { 
       top: 141px; 
       left: 118px; 
       position: absolute; 
       height: 25px; 
       width: 25px; 
      } 
     </style> 
    </head> 
    <body> 
     <form id="form1" runat="server"> 
      <div> 
       <img alt="asd" src="pic 3-4.jpg" id="AS" /> 
       <input type="button" value="Button" onclick="javascript:moveObjRight('AS');" /> 
      </div> 
     </form> 
    </body> 
</html> 

回答

3

您需要使用计算的样式属性。这可以通过具有简单功能的跨浏览器方法来实现。请参阅quirks mode以了解以下功能的解释。

function getStyle(el,styleProp) { 
    var x = document.getElementById(el); 
    if (x.currentStyle) 
     var y = x.currentStyle[styleProp]; 
    else if (window.getComputedStyle) 
     var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp); 
    return y; 
} 
0

只是一个建议(不是答案),请使用jQuery

您将能够通过以下代码访问左侧属性。

$('#yourdiv')。css('left');

参考:.css()

+0

它是* [模因(http://meta.stackexchange.com/questions/19478/the-many-memes-of-meta/19492#19492) *。 – 2012-11-21 18:07:07

相关问题