获取div相对文档的位置,两个方法
经测试 document.getElementById("btn").getBoundingClientRect()
在IE6下有2像素的bug,不知道为什么.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{margin:0;padding:0;} html{margin:10px;} #btn{ position:absolute; top: 100px; left: 200px; margin-left: 20px; margin-top: 20px; border: 3px solid #f00; } </style> </head> <body> <div style="height:2000px;"></div> <div style="position:relative;"> <div id="btn"></div> </div> <script> var offset = document.getElementById("btn").getBoundingClientRect(); alert(offset.top); // alert(offset.left); alert(getAbsolutePosition(document.getElementById("btn")).top) //console.log(offset); function getAbsolutePosition(obj){ var left = 0; var top = 0; while(obj){ left += obj.offsetLeft; top += obj.offsetTop; obj = obj.offsetParent; } return {left:left, top:top}; } </script> </body> </html>
时间: 2024-12-24 02:46:14