简体   繁体   中英

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

I can't access the left property of one image element in a JavaScript function when I set the property from within stylesheets but when I use inline styles on the image tag it works fine.

Here is my code:

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

You need to use the computed styles properties. This can be achieved in a cross browser method with a simple function. Have a look on quirks mode for an explanation of the following function.

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

For Mozilla Firefox, check the documentation for img .

In Internet Explorer, see <IMG> Property Pages Dialog Box .

Just a suggestion (not an answer), use jQuery !

You would be able to access the left property with the following code.

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

Reference: .css()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM