Gets the current position of an element based on page coordinates.
("myElementId")。很好用。也很简单,如果你想知道简单点的底层点的,可以看下面我从犀牛书上抄来的。
javascript的犀牛书看了两边居然没有发现,还是因为我看的第四版低了。
先用document.getElementById()获取元素,然后传入下面的函数
// Get the X coordinate of the element e.
function getX(e) {
var x = 0; // Start with 0
while(e) { // Start at element e
x += e.offsetLeft; // Add in the offset
e = e.offsetParent; // And move up to the offsetParent
}
return x; // Return the total offsetLeft
}
function getY(element) {
var y = 0;
for(var e = element; e; e = e.offsetParent) // Iterate the offsetParents
y += e.offsetTop; // Add up offsetTop values
// Now loop up through the ancestors of the element, looking for
// any that have scrollTop set. Subtract these scrolling values from
// the total offset. However, we must be sure to stop the loop before
// we reach document.body, or we'll take document scrolling into account
// and end up converting our offset to window coordinates.
for(e = element.parentNode; e && e != document.body; e = e.parentNode)
if (e.scrollTop) y -= e.scrollTop; // subtract scrollbar values
// This is the Y coordinate with document-internal scrolling accounted for.
return y;
}