猿问

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

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

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


慕哥9229398
浏览 955回答 2
2回答

小怪兽爱吃肉

Element.getBoundingClientRect().left

繁星点点滴滴

不会呀,估计你代码有其他问题<!doctype html><html><head><meta charset="utf-8"><title>无标题文档</title></head><body>&nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; &nbsp; body{margin:0;padding:0;position:relative;}&nbsp; &nbsp; &nbsp; &nbsp; #box{position:relative;width:200px;height:200px;background:#ddd;margin:25px auto;}&nbsp; &nbsp; &nbsp; &nbsp; #test{width:100px;height:100px;background:#000;margin:0 auto;}&nbsp; &nbsp; &nbsp; &nbsp; .big{position:relative;width:250px;height:250px;background:#dd4215;margin:20px auto;overflow:hidden;}&nbsp; &nbsp; </style>&nbsp; &nbsp; <div class="big">&nbsp; &nbsp; &nbsp; &nbsp; <div id="box">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div id="test"></div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; &nbsp; <button>点我看offsetTop</button>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; var oTest = document.getElementById('test');&nbsp; &nbsp; &nbsp; &nbsp; var oButton = document.getElementsByTagName('button')[0];&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; oButton.onclick = function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('top:' + oTest.offsetTop + '\r\nleft:' + oTest.offsetLeft)&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; </script></body></html>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答