<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>获取页面元素的位置</title> <style> div{padding:20px;} </style> </head> <body> <script> //页面的实际尺寸 function getPagearea(){ if(document.compatMode == 'Backcompat'){ return { width : Math.max(document.body.clientWidth,document.body.scrollWidth), height : Math.max(document.body.clientHeight,document.body.scrollHeight) } }else{ return { width : Math.max(document.documentElement.clientWidth,document.documentElement.scrollWidth), height : Math.max(document.documentElement.clientHeight,document.documentElement.scrollHeight) } } } //获取元素在页面里的绝对位置 function getElementLeft(element){ var actualLeft = element.offsetLeft; var current = element.offsetParent; while (current !== null){ actualLeft += current.offsetLeft; current = current.offsetParent; } return actualLeft; } function getElementTop(element){ var actualTop = element.offsetTop; var current = element.offsetParent; while (current !== null){ actualTop += current.offsetTop; current = current.offsetParent; } return actualTop; } // 由于在表格和iframe中,offsetParent对象未必等于父容器,所以上面的函数对于表格和iframe中的元素不适用 //获取元素在页面里的相对位置 function getElementViewLeft(){ var actualLeft = element.offsetLeft; var current = element.offsetParent; while (current !== null){ actualLeft += current.offsetLeft; current = current.offsetParent; } if(document.compatMode == 'Backcompat'){ var elementScrollLeft = document.documentElement.scrollLeft; }else{ var elementScrollLeft = document.body.scrollLeft; } return actualLeft - elementScrollLeft; } </script> </body> </html>