javascript 使用javascript,如何获取元素的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6146027/
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
Using javascript, how to get the position of an element
提问by dave
like the title says, how to get the element's x, y positions with respect to their location in the web page and their positioning schemes like absolute, relative etc.
就像标题所说的那样,如何根据元素在网页中的位置及其绝对、相对等定位方案获取元素的 x、y 位置。
回答by Boris Zbarsky
In a modern browser, getBoundingClientRect and getClientRects will give you rect objects describing your element. See https://developer.mozilla.org/en/DOM/element.getBoundingClientRectand https://developer.mozilla.org/en/DOM/element.getClientRects
在现代浏览器中, getBoundingClientRect 和 getClientRects 将为您提供描述元素的矩形对象。请参阅https://developer.mozilla.org/en/DOM/element.getBoundingClientRect和https://developer.mozilla.org/en/DOM/element.getClientRects
If you have to work with IE8, then you'll have to do different things in different browsers to get correct answers (e.g. object-detect getBoundingClientRect and fall back on some other method if it's not present).
如果您必须使用 IE8,那么您必须在不同的浏览器中做不同的事情才能得到正确的答案(例如,对象检测 getBoundingClientRect 并在它不存在时退回到其他一些方法)。
The jQuery offset()
calculation and the Quirksmode findPos
will give incorrect answers in any browser that does subpixel positioning (e.g. Firefox or IE9), because they will round the answer to an integer number of pixels. Depending on what you're doing, that may or may not be ok.
jQueryoffset()
计算和 QuirksmodefindPos
在任何进行亚像素定位的浏览器(例如 Firefox 或 IE9)中都会给出错误的答案,因为它们会将答案四舍五入为整数像素。取决于你在做什么,这可能好也可能不好。
回答by Matt Ball
With jQuery:
使用 jQuery:
var $elt = $('select an element however'),
cssPosition = $elt.css('position'),
offset = $elt.offset(),
top = offset.top,
left = offset.left;
Without jQuery, use Quirksmode's findPos
function:
如果没有 jQuery,请使用Quirksmode 的findPos
函数:
var elt = document.getElementBy...,
pos = findPos(elt),
top = pos[1],
left = pos[0];
Getting the computed CSS position
value without a library is another can of worms. It boils down to:
在position
没有库的情况下获取计算的 CSS值是另一种蠕虫。归结为:
element.currentStyle
(IE)getComputedStyle(element)
(real browsers)
回答by Anand Thangappan
Check out this
看看这个
JS:
JS:
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
HTML:
HTML:
<div id="ser"> TEST</div>
RETURN CALL:
回电:
alert(findPos(document.getElementById('ser')));
I hope its help to you
我希望它对你有帮助