Javascript 如何获得 Element 的正确位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7090450/
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 to get right position of Element?
提问by Xavier
I wish to get the right position of an element. I have tried attr('right')
and I have read the API document regarding .position().right
which is non existent (I believe).
我希望获得元素的正确位置。我已经尝试过attr('right')
并且我已经阅读了关于.position().right
不存在的 API 文档(我相信)。
http://jsfiddle.net/xavi3r/vcuq7/
http://jsfiddle.net/xavi3r/vcuq7/
Is an example I wish to alert the right value for.
是我希望提醒正确值的示例。
回答by nickf
You want to find the value of the CSS right
property?
您想查找 CSSright
属性的值吗?
$('#foo').css('right');
In plain Javascript:
在纯 Javascript 中:
document.getElementById('foo').style.right;
But, if you want to find the calculateddistance from the right edge of an element to the right edge of another one, then you'll have to do that yourself, combining .position().left
and .offsetWidth
但是,如果你想找到从一个元素的右边缘到另一个元素的右边缘的计算距离,那么你必须自己做,结合.position().left
和.offsetWidth
回答by Mladen Adamovic
It looks to me that this works:
在我看来这是有效的:
jQuery('#elem').offset().left + jQuery('#elem').width()
回答by Nikita Tomkevich
$(document).width() - ($('#elem').offset().left + $('#elem').width());
should get you the space on the right side of the element which you can then set as the value for the 'right' property of the element's position;
应该为您提供元素右侧的空间,然后您可以将其设置为元素位置的 'right' 属性的值;
回答by Jorgeblom
The CSS value is only valid if it's set via style or $.css().
CSS 值仅在通过样式或 $.css() 设置时才有效。
But if you need to get the right position of an object, you should do it using javascript / jquery.
但是如果你需要得到一个对象的正确位置,你应该使用 javascript/jquery 来做。
Although there are some valid solutions, it's important to note that $.fn.width() doesn't take padding and borders in account. So it's better to use outerWidth().
尽管有一些有效的解决方案,但重要的是要注意 $.fn.width() 不考虑填充和边框。所以最好使用outerWidth()。
Example:
例子:
$(document).width() - ($('#elem').offset().left + $('#elem').outerWidth());
You can even create a $.fn function to get the value:
你甚至可以创建一个 $.fn 函数来获取值:
$.fn.right = function() {
return $(document).width() - (this.offset().left + this.outerWidth());
}
And then use it:
然后使用它:
$('#elem').right();
回答by Rafay
you can try .css
你可以试试 .css
.css("right");
.css("right");
回答by mcmimik
As noted by @avernet in comments, the equivalent of an hypothetical .position().right would be expression like this:
正如@avernet 在评论中所指出的,假设 .position().right 的等价物将是这样的表达式:
$('#foo').offsetParent().width() - ($('#foo').position().left + $('#foo').width());