给定一个HTML DOM ID,如何在JavaScript/JQuery中获取元素相对于窗口的位置?这与相对于文档或偏移父元素不同,因为元素可能在iframe或其他一些元素中。我需要获取当前显示的元素矩形的屏幕位置(如位置和尺寸)。如果元素当前不在屏幕上(已滚动关闭),则负值是可接受的。
这是针对iPad (WebKit / WebView)应用程序的。每当用户点击UIWebView
中的特殊链接时,我都会打开一个弹出式视图,其中显示有关该链接的更多信息。popover视图需要显示一个箭头,该箭头指向调用它的屏幕部分。
发布于 2015-07-14 21:28:50
尝试使用边界框。这很简单:
var leftPos = $("#element")[0].getBoundingClientRect().left + $(window)['scrollLeft']();
var rightPos = $("#element")[0].getBoundingClientRect().right + $(window)['scrollLeft']();
var topPos = $("#element")[0].getBoundingClientRect().top + $(window)['scrollTop']();
var bottomPos= $("#element")[0].getBoundingClientRect().bottom + $(window)['scrollTop']();
发布于 2013-10-08 15:49:37
function getWindowRelativeOffset(parentWindow, elem) {
var offset = {
left : 0,
top : 0
};
// relative to the target field's document
offset.left = elem.getBoundingClientRect().left;
offset.top = elem.getBoundingClientRect().top;
// now we will calculate according to the current document, this current
// document might be same as the document of target field or it may be
// parent of the document of the target field
var childWindow = elem.document.frames.window;
while (childWindow != parentWindow) {
offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
childWindow = childWindow.parent;
}
return offset;
};
你可以这样叫它
getWindowRelativeOffset(top, inputElement);
我只根据我的需求关注IE,但对于其他浏览器也可以做类似的事情
发布于 2010-09-15 13:11:03
这听起来更像是您想要所选链接的工具提示。有许多jQuery工具提示,请尝试jQuery qTip。它有很多选择,并且很容易改变样式。
否则,如果您希望自己执行此操作,则可以使用jQuery .position()
。有关.position()
的更多信息,请访问http://api.jquery.com/position/
$("#element").position();
将返回元素相对于偏移父级的当前位置。
还有jQuery .offset();,它将返回相对于文档的位置。
https://stackoverflow.com/questions/3714628
复制相似问题