用jquery查找div底部的位置

lag*_*223 64 jquery

我有一个div,想找到最低位置.我可以找到这样的Div的顶部位置,但我如何找到底部位置?

var top = $('#bottom').position().top;
return top;
Run Code Online (Sandbox Code Playgroud)

use*_*361 148

将外部高度添加到顶部,并且相对于父元素具有底部:

var $el = $('#bottom');  //record the elem so you don't crawl the DOM everytime  
var bottom = $el.position().top + $el.outerHeight(true); // passing "true" will also include the top and bottom margin
Run Code Online (Sandbox Code Playgroud)

使用绝对定位的元素或相对于文档定位时,您需要使用偏移量来评估:

var bottom = $el.offset().top + $el.outerHeight(true);
Run Code Online (Sandbox Code Playgroud)

正如trnelson所指出的,这在100%的时间里都不起作用.要将此方法用于定位元素,还必须考虑偏移量.有关示例,请参阅以下代码.

var bottom = $el.position().top + $el.offset().top + $el.outerHeight(true);
Run Code Online (Sandbox Code Playgroud)

  • 我提交了一个编辑,但它被拒绝了.在这种情况下,这个答案在技术上是正确的,但并不能在100%的时间内解决问题.要对定位元素使用此方法,还必须考虑偏移:`var bottom = $('#bottom').position().top + $('#bottom').offset().top + $('#bottom ").outerHeight(真)` (6认同)
  • 截至2017-07-19,在这个答案的最后一行中,"true"这个词有一个邪恶的隐形字符,如果你复制/粘贴它会破坏你的代码(它为我做了,使用Atom).该字符位于单词"true"中的"t"和"r"之间.我尝试编辑答案,但被拒绝了.我会假设那些拒绝它的人没有阅读我的编辑描述,没有其他逻辑的,非邪恶的理由故意保留一个会破坏人们代码的隐形字符. (4认同)
  • @MikeWillis幸运的是,我阅读了您的评论,并且由于我的声誉比您高,因此我希望我的编辑能够保留到最后。Erm,SO结束。嗯,同样的事情... :) (2认同)

yoy*_*nno 13

编辑:此解决方案现在也在原始答案中.

接受的答案并不完全正确.您不应该使用position()函数,因为它是相对于父级的.如果您正在进行全球定位(在大多数情况下?),您应该只添加具有外部高度的偏移顶部,如下所示:

var actualBottom = $(selector).offset().top + $(selector).outerHeight(true);
Run Code Online (Sandbox Code Playgroud)

文档http://api.jquery.com/offset/


Jis*_*ish 5

var bottom = $('#bottom').position().top + $('#bottom').height();
Run Code Online (Sandbox Code Playgroud)


Sly*_*Sly 5

如果您只想使用高度而不使用填充,边框等,那么到目前为止的答案都可以使用。

如果要考虑填充,边框和边距,则应使用.outerHeight

var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);
Run Code Online (Sandbox Code Playgroud)