如何正确计算元素(父级有相对定位)的offset值

在计算元素的offset的时候,如果其多个父级定位有相对定位,则该元素的offset的值会受相对定位的影响。

clipboard.png
比如想算div.container 的offset,则会有60像素的偏移。

阅读 3.1k
2 个回答

不会呀,估计你代码有其他问题

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
    <style>
        body{margin:0;padding:0;position:relative;}
        #box{position:relative;width:200px;height:200px;background:#ddd;margin:25px auto;}
        #test{width:100px;height:100px;background:#000;margin:0 auto;}
        .big{position:relative;width:250px;height:250px;background:#dd4215;margin:20px auto;overflow:hidden;}
    </style>
    <div class="big">
        <div id="box">
            <div id="test"></div>
        </div>
    </div>
    <button>点我看offsetTop</button>
    
    <script>
        var oTest = document.getElementById('test');
        var oButton = document.getElementsByTagName('button')[0];
        
        oButton.onclick = function () {
            alert('top:' + oTest.offsetTop + '\r\nleft:' + oTest.offsetLeft)
        };
    </script>
</body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题