用jQuery查找div底部的位置


74

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

var top = $('#bottom').position().top;
return top;

Answers:


162

相对于父元素,将outerheight添加到顶部,并在底部:

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

对于绝对定位的元素或相对于文档定位的元素,您将需要使用offset进行评估:

var bottom = $el.offset().top + $el.outerHeight(true);

正如特雷尔森所指出的那样,这在100%的时间内都无效。要对定位的元素使用此方法,还必须考虑偏移量。有关示例,请参见以下代码。

var bottom = $el.position().top + $el.offset().top + $el.outerHeight(true);

6
我提交了修改,但被拒绝了。在这种情况下,此答案在技术上是正确的,但不能100%地解决问题。要对定位的元素使用此方法,还必须考虑偏移量:var bottom = $('#bottom').position().top+$('#bottom').offset().top+$('#bottom').outerHeight(true)
trnelson 2015年

很奇怪...我没有积极拒绝修改。无论如何,您绝对(对)正确。处理定位的元素时,必须考虑偏移量
user1026361 2015年

4
截至2017年7月19日,此答案的最后一行中的“ true”一词具有一个不可见的邪恶字符,如果您复制/粘贴,它将破坏您的代码(使用Atom对我有用)。该字符位于单词“ true”中的“ t”和“ r”之间。我尝试编辑答案,但被拒绝。我假设那些拒绝它的人没有读过我的编辑描述,没有其他逻辑,非邪恶的理由故意保留一个会破坏人们代码的不可见字符。
Mike Willis'7

2
@MikeWillis幸运的是,我阅读了您的评论,并且由于我的声誉比您高,因此我希望我的编辑能够保留到最后。Erm,SO的结尾。嗯,同样的事情... :)
sjngm

@sjngm哈哈不错,是的,我希望它也保持在原位!
迈克·威利斯

13

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

接受的答案不是很正确。您不应该使用position()函数,因为它是相对于父函数的。如果要进行全局定位(在大多数情况下?),则应仅添加具有topoutheight的偏移顶部,如下所示:

var actualBottom = $(selector).offset().top + $(selector).outerHeight(true);

docs http://api.jquery.com/offset/


5
var bottom = $('#bottom').position().top + $('#bottom').height();

5

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

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

var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);

1

底部是top+ outerHeight而不是height,因为它不包括边距或填充。

var $bot,
    top,
    bottom;
$bot = $('#bottom');
top = $bot.position().top;
bottom = top + $bot.outerHeight(true); //true is necessary to include the margins


0

这是jquery实际上使其比DOM已经提供的更加复杂的实例之一。

let { top, bottom, height, width, //etc } = $('#bottom')[0].getBoundingClientRect();
return top;

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.