Javascript jQuery 获取元素相对于窗口的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3714628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery get the location of an element relative to window
提问by adib
Given an HTML DOM ID, how to get an element's position relative to the window in JavaScript/JQuery? This is not the same as relative to the document nor offset parent since the element may be inside an iframe or some other elements. I need to get the screen location of the element's rectangle (as in position and dimension) as it is currently being displayed. Negative values are acceptable if the element is currently off-screen (have been scrolled off).
给定一个 HTML DOM ID,如何在 JavaScript/JQuery 中获取元素相对于窗口的位置?这与相对于文档或偏移父元素不同,因为元素可能位于 iframe 或其他一些元素内。我需要获取当前正在显示的元素矩形的屏幕位置(如位置和尺寸)。如果元素当前在屏幕外(已滚动关闭),则可以接受负值。
This is for an iPad (WebKit / WebView) application. Whenever the user taps on a special link in an UIWebView, I am supposed to open a popover view that displays further information about the link. The popover view needs to display an arrow that points back to the part of the screen that invokes it.
这是一个 iPad (WebKit / WebView) 应用程序。每当用户点击 中的特殊链接时UIWebView,我应该打开一个弹出视图,显示有关该链接的更多信息。弹出视图需要显示一个箭头,指向调用它的屏幕部分。
回答by
Initially, Grab the .offsetposition of the element and calculate its relative position with respect to window
最初,抓取元素的.offset位置并计算其相对于窗口的相对位置
Refer:
1. offset
2. scroll
3. scrollTop
请参考:
1.偏移
2.滚动
3. scrollTop的
You can give it a try at this fiddle
你可以试试这个小提琴
Following few lines of code explains how this can be solved
以下几行代码解释了如何解决这个问题
when .scrollevent is performed, we calculate the relative position of the element with respect to window object
当.scroll事件被执行时,我们计算元素相对于 window 对象的相对位置
$(window).scroll(function () {
console.log(eTop - $(window).scrollTop());
});
when scroll is performed in browser, we call the above event handler function
当在浏览器中执行滚动时,我们调用上面的事件处理函数
code snippet
代码片段
function log(txt) {
$("#log").html("location : <b>" + txt + "</b> px")
}
$(function() {
var eTop = $('#element').offset().top; //get the offset top of the element
log(eTop - $(window).scrollTop()); //position of the ele w.r.t window
$(window).scroll(function() { //when window is scrolled
log(eTop - $(window).scrollTop());
});
});
#element {
margin: 140px;
text-align: center;
padding: 5px;
width: 200px;
height: 200px;
border: 1px solid #0099f9;
border-radius: 3px;
background: #444;
color: #0099d9;
opacity: 0.6;
}
#log {
position: fixed;
top: 40px;
left: 40px;
color: #333;
}
#scroll {
position: fixed;
bottom: 10px;
right: 10px;
border: 1px solid #000;
border-radius: 2px;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="log"></div>
<div id="element">Hello
<hr>World</div>
<div id="scroll">Scroll Down</div>
回答by prograhammer
Try the bounding box. It's simple:
尝试边界框。这很简单:
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']();
回答by Imran Ansari
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;
};
you can call it like this
你可以这样称呼它
getWindowRelativeOffset(top, inputElement);
I focus for IE only as per my requirement but similar can be done for other browsers
我只根据我的要求关注 IE,但其他浏览器也可以这样做
回答by jhanifen
This sounds more like you want a tooltip for the link selected. There are many jQuery tooltips, try out jQuery qTip. It has a lot of options and is easy to change the styles.
这听起来更像是您想要所选链接的工具提示。有很多 jQuery 工具提示,试试jQuery qTip。它有很多选项,很容易改变样式。
Otherwise if you want to do this yourself you can use the jQuery .position(). More info about .position()is on http://api.jquery.com/position/
否则,如果您想自己执行此操作,则可以使用 jQuery .position(). 有关更多信息,请.position()访问http://api.jquery.com/position/
$("#element").position();will return the current position of an element relative to the offset parent.
$("#element").position();将返回元素相对于偏移父元素的当前位置。
There is also the jQuery .offset();which will return the position relative to the document.
还有 jQuery .offset(); 这将返回相对于文档的位置。
回答by Bob Stein
TL;DR
TL; 博士
headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();
headroom_by_DOM = $('#id')[0].getBoundingClientRect().top; // if no iframe
.getBoundingClientRect()appears to be universal. .offset()and .scrollTop()have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.
.getBoundingClientRect()似乎是通用的。 从 jQuery 1.2 开始支持.offset()和.scrollTop()。感谢@user372551 和@prograhammer。要在 iframe 中使用 DOM,请参阅@ImranAnsari 的解决方案。
回答by mmm
function trbl(e, relative) {
var r = $(e).get(0).getBoundingClientRect(); relative = $(relative);
return {
t : r.top + relative['scrollTop'] (),
r : r.right + relative['scrollLeft'](),
b : r.bottom + relative['scrollTop'] (),
l : r.left + relative['scrollLeft']()
}
}
// Example
trbl(e, window);
回答by Ketan Savaliya
Try this to get the location of an element relative to window.
试试这个来获取元素相对于窗口的位置。
$("button").click(function(){
var offset = $("#simplebox").offset();
alert("Current position of the box is: (left: " + offset.left + ", top: " + offset.top + ")");
});
#simplebox{
width:150px;
height:100px;
background: #FBBC09;
margin: 150px 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">Get Box Position</button>
<p><strong>Note:</strong> Play with the value of margin property to see how the jQuery offest() method works.</p>
<div id="simplebox"></div>
See more @ Get the position of an element relative to the document with jQuery
查看更多@使用jQuery获取元素相对于文档的位置

