Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么可以';我不能在JavaScript函数中访问这个CSS属性吗?_Javascript - Fatal编程技术网

为什么可以';我不能在JavaScript函数中访问这个CSS属性吗?

为什么可以';我不能在JavaScript函数中访问这个CSS属性吗?,javascript,Javascript,当我从样式表中设置属性时,我无法访问JavaScript函数中一个图像元素的left属性,但当我在图像标记上使用内联样式时,它工作正常 这是我的密码: <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script type="text/javascript">

当我从样式表中设置属性时,我无法访问JavaScript函数中一个图像元素的
left
属性,但当我在图像标记上使用内联样式时,它工作正常

这是我的密码:

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

功能moveObjRight(obj){
var a=document.getElementById(obj);
警报(a.style.左)
}
#作为
{
顶部:141px;
左:118px;
位置:绝对位置;
高度:25px;
宽度:25px;
}

对于Mozilla Firefox,请检查


在InternetExplorer中,请参见。

您需要使用“计算样式”属性。这可以通过使用简单功能的跨浏览器方法实现。查看以下函数的说明

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;
}
只是一个建议(不是答案),使用

您可以使用以下代码访问left属性

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

参考资料:

是的。