您的位置:首页 > Web前端 > JavaScript

javascript获取元素距离网页的left距离

2012-03-28 10:20 344 查看
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>test</title>
    <link href="Styles/Site.css" type="text/css" />
    <style type="text/css">
        *{ margin:0; padding:0; }
        #div1{ width:500px; height:500px; margin:100px; position:relative; background-color:#CCCCCC; }
        #div2{ width:300px; height:300px; position:absolute; left:30px; background-color:#0099ff;}
        #div3{ width:100px; height:100px; position:absolute; left:30px; background-color:Red; }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            var left = 0; //存放left值
            var obj = document.getElementById("div3");
            while (obj) { //如果这个obj存在的话
                left = parseInt(left) + obj.offsetLeft;
                obj = obj.offsetParent; //obj变成自己的parent,一层一层向上循环累加left的值,直到obj不存在
            }
            document.getElementById("div3").innerHTML = left;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="div1">
            <div id="div2">
                <div id="div3">
                    0
                </div>
            </div>
        </div>
    </form>
</body>
</html>


新博客已移至:http://keenwon.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: