Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Is it possible to get the position of div within the browser viewport? Not within the document. Within the window

Is this doable in either IE7 or Firefox?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it in both - get the position relative to the document, then subtract the scroll position.

var e = document.getElementById('xxx');
var offset = {x:0,y:0};
while (e)
{
    offset.x += e.offsetLeft;
    offset.y += e.offsetTop;
    e = e.offsetParent;
}

if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft))
{
    offset.x -= document.documentElement.scrollLeft;
    offset.y -= document.documentElement.scrollTop;
}
else if (document.body && (document.body.scrollTop || document.body.scrollLeft))
{
    offset.x -= document.body.scrollLeft;
    offset.y -= document.body.scrollTop;
}
else if (window.pageXOffset || window.pageYOffset)
{
    offset.x -= window.pageXOffset;
    offset.y -= window.pageYOffset;
}

alert(offset.x + '
' + offset.y);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...