簡體   English   中英

為什么我不能在JavaScript函數中訪問此CSS屬性?

[英]Why can't I access this CSS property in a JavaScript function?

當我從樣式表中設置屬性時,無法訪問JavaScript函數中一個圖像元素的left屬性,但是當我在image標簽上使用內聯樣式時,它可以正常工作。

這是我的代碼:

<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>

您需要使用計算的樣式屬性。 這可以通過具有簡單功能的跨瀏覽器方法來實現。 請看一下怪癖模式 ,以解釋以下功能。

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;
}

對於Mozilla Firefox,請查看img文檔

在Internet Explorer中,請參見<IMG>屬性頁對話框

只是一個建議(不是答案),請使用jQuery

您可以使用以下代碼訪問left屬性。

$( '#yourdiv')的CSS( '左');

參考: .css()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM