var element = document.getElementById('elementId'); //replace elementId with your element's Id.var rect = element.getBoundingClientRect();var elementLeft,elementTop; //x and yvar scrollTop = document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop;var scrollLeft = document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft;elementTop = rect.top+scrollTop;elementLeft = rect.left+scrollLeft;
function findLeft(element) {var rec = document.getElementById(element).getBoundingClientRect();return rec.left + window.scrollX;} //call it like findLeft('#header');
2)查找顶部
function findTop(element) {var rec = document.getElementById(element).getBoundingClientRect();return rec.top + window.scrollY;} //call it like findTop('#header');
或3)找到左和顶在一起
function findTopLeft(element) {var rec = document.getElementById(element).getBoundingClientRect();return {top: rec.top + window.scrollY, left: rec.left + window.scrollX};} //call it like findTopLeft('#header');
var elm = $('#div_id'); //get the divvar posY_top = elm.offset().top; //get the position from topvar posX_left = elm.offset().left; //get the position from left
window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y
window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X
HTML program to show (x, y) of anelement by dragging mouse over it you just copied it and use it on your own<!DOCTYPE html><html><head><title>position of an element</title>
<!-- scropt to get position --><script type = "text/javascript">function getPositionXY(element) {var rect = element.getBoundingClientRect();document.getElementById('text').innerHTML= 'X: ' + rect.x + '<br>' + 'Y: ' + rect.y;}</script></head>
<body><p>Move the mouse over the text</p>
<div onmouseover = "getPositionXY(this)">Position:<p id = 'text'></p></div>
</body></html>