简体   繁体   English

是否可以在浏览器视口中获取div的位置?不在文件中。在窗口内

[英]Is it possible to get the position of div within the browser viewport? Not within the document. Within the window

这在IE7或Firefox中都可行吗?

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 + '\n' + offset.y);

[Pasting from the answer I gave here ] [从我在这里给出的答案粘贴]

The native getBoundingClientRect() method has been around for quite a while now, and does exactly what the question asks for. 本机getBoundingClientRect()方法现在已经存在了很长一段时间,并且完全正如问题所要求的那样。 Plus it is supported across all browsers (including IE 5, it seems!) 此外,它支持所有浏览器(包括IE 5,似乎!)

From this MDN page: 这个 MDN页:

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport . 返回的值是一个TextRectangle对象,它包含描述border-box的只读左,上,右和底属性,以像素为单位,左上角相对于视口的左上角

You use it like so: 你这样使用它:

var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport, i.e. the window
var top = viewportOffset.top;
var left = viewportOffset.left;

Try the dimensions jQuery plugin . 试试尺寸jQuery插件 See this demo . 这个演示

$('#myelement.').offset();

In IE and Firefox 3, you can use getBoundingClientRect for this; 在IE和Firefox 3中,您可以使用getBoundingClientRect ; no framework necessary. 没有必要的框架。

But, yes, you should use a framework if you need to support other browsers as well. 但是,是的,如果您还需要支持其他浏览器,则应该使用框架。

You could subtract the div's offsetTop from the document.body.scrollTop 你可以从document.body.scrollTop中减去div的offsetTop

This seems to work on IE7 and FF3, but on a very simple page. 这似乎适用于IE7和FF3,但在一个非常简单的页面上。 I haven't checked with nested DIVs. 我没有检查过嵌套的DIV。

Using Prototype it would be: 使用Prototype它将是:

$('divname').viewportOffset.top
$('divname').viewportOffset.left

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM