用jquery查找div底部的位置

时间:2012-10-05 15:55:06

标签: jquery

我有一个div,想找到最低位置。我可以像这样找到Div的最高位置,但我如何找到最低位置?

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

8 个答案:

答案 0 :(得分:143)

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

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);

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

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

答案 1 :(得分:11)

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

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

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

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

答案 2 :(得分:4)

到目前为止的答案将起作用..如果你只想使用没有填充,边框等的高度。

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

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

答案 3 :(得分:3)

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

答案 4 :(得分: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

答案 5 :(得分:0)

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

答案 6 :(得分:0)

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

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

答案 7 :(得分:0)

使用此脚本计算div的结尾

$('#bottom').offset().top +$('#bottom').height()