javascript 如何获得绝对定位元素的左/右/上/下的实际值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23891892/
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
How do I get the actual values for left/right/top/bottom of an absolutely positioned element?
提问by Peter Boughton
(This seems like a simple question that would have been asked before, but if it has I can't find it, though there are lots of similar ones that don't answer what I want.)
(这似乎是一个以前会被问到的简单问题,但如果有,我找不到它,尽管有很多类似的问题没有回答我想要的问题。)
In Firefox (24.0), this code gives me what I want - the relevant number of pixels:
在 Firefox (24.0) 中,这段代码给了我我想要的 - 相关的像素数:
jQuery('selector').css('right')
In Chrome (34.0.1847.137 m), it only gives pixels for left/top but returns auto
for right/bottom.
在 Chrome (34.0.1847.137 m) 中,它只给出左/上像素,但返回auto
右/下像素。
There are various questions on SO explaining that this is the expected behaviour of .css, but I cannot find anything that explains how to get my desired behaviour - i.e. give me calculated pixel values for all four values.
SO 上有各种问题解释说这是 .css 的预期行为,但我找不到任何可以解释如何获得我想要的行为的东西 - 即给我所有四个值的计算像素值。
Do JS or jQuery have any way to directly get these four values, that works consistently in all browsers/scenarios? (Or do I have to resort to ugly manual calculations?)
JS 或 jQuery 有什么方法可以直接获取这四个值,在所有浏览器/场景中都一致吗?(还是我必须求助于丑陋的手动计算?)
Clarification:
I need values that are equivalent to the .css('right')
values that Firefox returns - which is the distance between the right-edges of the current and parent element. This is not the same as viewport-relative left+width definitions which some functions return.
说明:
我需要.css('right')
与 Firefox 返回的值等效的值 - 即当前元素和父元素的右边缘之间的距离。这与某些函数返回的相对于视口的 left+width 定义不同。
i.e. the logged values here should be numerically the same:
即这里的记录值在数字上应该是相同的:
elem = jQuery('selector')
rect = someFunction( elem[0] );
console.log([ elem.css('left') , rect.left ]);
console.log([ elem.css('right') , rect.right ]);
console.log([ elem.css('top') , rect.top ]);
console.log([ elem.css('bottom') , rect.bottom ]);
Unless I'm misreading the other answers, only kalley's getRelativeClientRect answermeets this criteria.
除非我误读了其他答案,否则只有kalley 的 getRelativeClientRect 答案符合此标准。
回答by kalley
you can use getBoundingClientRect
. It will take into account any transforms as well, if you are using them.
你可以使用getBoundingClientRect
. 如果您正在使用它们,它也会考虑任何转换。
You'd need to call it like jQuery('selector')[0].getBoundingClientRect()
. Or use vanilla javascript like document.querySelector('selector').getBoundingClientRect()
, which will return a single element or document.querySelectorAll('selector')[index].getBoundingClientRect()
.
你需要这样称呼它jQuery('selector')[0].getBoundingClientRect()
。或者使用普通的 javascript 之类的document.querySelector('selector').getBoundingClientRect()
,它将返回单个元素或document.querySelectorAll('selector')[index].getBoundingClientRect()
.
To summarize, in a slightly more readable format:
总而言之,以更易读的格式:
jQuery('selector')[0].getBoundingClientRect()
document.querySelector('selector').getBoundingClientRect()
document.querySelectorAll('selector')[index].getBoundingClientRect()
jQuery('selector')[0].getBoundingClientRect()
document.querySelector('selector').getBoundingClientRect()
document.querySelectorAll('selector')[index].getBoundingClientRect()
or replace the QS calls with older ones like getElementById
, etc.
或将 QS 调用替换为较旧的调用,例如getElementById
等。
Here's a function you could use if you wanted to get it relative to it's parent:
如果您想相对于其父级获取它,则可以使用以下函数:
function getRelativeClientRect(el) {
var rect = el.getBoundingClientRect(),
parentRect = el.offsetParent.getBoundingClientRect();
return {
bottom: parentRect.bottom - rect.bottom,
height: rect.height,
left: rect.left - parentRect.left,
right: parentRect.right - rect.right,
top: rect.top - parentRect.top,
width: rect.width
};
}
回答by cocco
EDIT: this is about absolute position
编辑:这是关于 absolute position
Very old function findPos
很老的函数 findPos
http://www.quirksmode.org/js/findpos.html
http://www.quirksmode.org/js/findpos.html
Variante considering scroll & borders
考虑滚动和边框的变体
function getPosition(el){
var x=0,y= 0;
while(el) {
x+=(el.offsetLeft-el.scrollLeft+el.clientLeft);
y+=(el.offsetTop-el.scrollTop+el.clientTop);
el=el.offsetParent;
}
return{x:x,y:y}
}
to get right
做对
var info=getPosition(element);
console.log('marginRight: '+info.x-element.offsetWidth);
Note1: these are vanilla javascript functions that are compatible with older browsers. thats why jQuery is not needed.obiovsly the performance is much better than using jQuery.
注意 1:这些是与旧浏览器兼容的 vanilla javascript 函数。这就是为什么不需要 jQuery。obiovsly 性能比使用 jQuery 好得多。
Note2: there are many other versions if you search find position
注意2:如果您搜索查找位置,还有许多其他版本
getBoundingClientRect
getBoundingClientRect
to get the right
得到正确的
var info=element.getBoundingClientRect(); // Native Javascript ..think 1.6+
console.log('marginRight: 'info.right-info.width);
Conclusion
结论
There is no easy way to get the dimensions,offsets,applied css of an element if you want a allround compatible script.
如果您想要一个全面兼容的脚本,没有简单的方法来获取元素的尺寸、偏移量、应用的 css。
the getPosition
function is probably the best function (considering compatibility) that allows you to easely calculate this values..
该getPosition
函数可能是最好的函数(考虑到兼容性),可以让您轻松计算此值。
Note:as there is a while loop inside the function, on very old machines you could get some problems with heavely nested elements.
注意:由于函数内部有一个 while 循环,在非常旧的机器上,您可能会遇到大量嵌套元素的问题。
if your using html5 and css than go for getBoundingClientRect
如果你使用 html5 和 css 比去 getBoundingClientRect
Note:probably both break when using css3 transforms.
注意:使用 css3 转换时可能两者都会中断。
EDIT
编辑
I need values that are equivalent to the .css('right') values that Firefox returns
我需要与 Firefox 返回的 .css('right') 值等效的值
To get those values you first need to find the position of the element.
要获得这些值,您首先需要找到元素的位置。
So:getPosition
function or getBoundingClientRect
所以:getPosition
函数或getBoundingClientRect
then you need to calculate the top/bottom,left/right values.
那么您需要计算顶部/底部,左侧/右侧的值。
left=x
right=x-width
top=y
bottom=y-height
EDIT2:
编辑2:
To apply this only to the parent element you need to execute getPosition
also on the parent element
若要将此只向父元素,您需要执行getPosition
还父元素
and the calculations are shown in @kalley's answer.
计算结果显示在@kalley 的回答中。
回答by Cannicide
There is a built-in way to do this in Javascript without JQUERY. There are two special ones I'll show you, one is JS and CSS, other is just JS.
在没有 JQUERY 的 Javascript 中有一种内置的方法可以做到这一点。我将向您展示两种特殊的,一种是 JS 和 CSS,另一种只是 JS。
element.style.left; //Gives you distance from left edge of your viewport.
element.style.top + "px"; //Gives you distance in pixels from top edge
element.style.right; //etc.
//There is also the way of Offset. You do not need CSS at all for this.
//Of course, Jquery has its own way of doing this, but I'll show JS-only
element.offsetTop; //Gives distance from top of viewport to top of element
element.offsetLeft; //Gives distance from left of viewport to left of element
//etc.
As always, there are many more ways to do this with and without Jquery. I prefer not using Jquery at all (despite the fact that it is awesome), and I know others prefer not using Jquery too. If you want to use Jquery, I'd recommend using the Jquery way like @farincz did. If not, this way or getBoundingClientRect
is better. Best thing about using .style.top
or .style.left
is that you can not only get the actual values for left/right/top/bottom, but you can also set them. This is great for stuff like drag-and-drop.
与往常一样,使用 Jquery 和不使用 Jquery,有更多方法可以做到这一点。我根本不喜欢使用 Jquery(尽管它很棒),而且我知道其他人也不喜欢使用 Jquery。如果您想使用 Jquery,我建议您像 @farincz 那样使用 Jquery 方式。如果没有,这种方式还是getBoundingClientRect
比较好。使用.style.top
or 的最佳之.style.left
处在于您不仅可以获得左/右/上/下的实际值,而且您还可以设置它们。这对于拖放之类的东西非常有用。
回答by farincz
You can get it with $().offset - it returns position in document. Suppose p be parent element towards which is your element positioned.
您可以使用 $().offset 获取它 - 它返回文档中的位置。假设 p 是您的元素定位的父元素。
then left is
然后左边是
var left = $(el).offset().left - $(p).offset().left;
right is more complicated, you must use also width
右边更复杂,你也必须使用宽度
var right = ($(p).offset().left + $(p).width()) - ($(el).offset().left + $(el).width());
last thing is obtain p elment. You know it directly or find it in $(el).parents() It has position relative or absolute.
最后一件事是获得 pelment。你直接知道它或在 $(el).parents() 中找到它它有相对或绝对的位置。
回答by Piyush Kumar Baliyan
Use function getBoundingClientRect(), it gives you left, right, top, bottom, width, height values:
使用函数getBoundingClientRect(),它为您提供左、右、上、下、宽度、高度值:
var myid=document.getElementById("id").getBoundingClientRect();
var bottom=myid.bottom;
var top=myid.top;
var right=myid.right
... and so on.
... 等等。
Source: MDN | Element.getBoundingClientRect()
来源:MDN | Element.getBoundingClientRect()
EDITED:
编辑:
To get coordinates with respect to the page and not viewport:
要获取关于页面而不是视口的坐标:
var bodycoord=document.body.getBoundingClientRect();
var top-from-page=myid.top-bodycoord.top;
var left-from-page=myid.left-bodycoord.top;