我有一个div,想找到底部的位置。我可以这样找到Div的顶部位置,但是如何找到底部位置?
var top = $('#bottom').position().top;
return top;
我有一个div,想找到底部的位置。我可以这样找到Div的顶部位置,但是如何找到底部位置?
var top = $('#bottom').position().top;
return top;
Answers:
相对于父元素,将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);
编辑:此解决方案现在也在原始答案中。
接受的答案不是很正确。您不应该使用position()函数,因为它是相对于父函数的。如果要进行全局定位(在大多数情况下?),则应仅添加具有topoutheight的偏移顶部,如下所示:
var actualBottom = $(selector).offset().top + $(selector).outerHeight(true);
底部是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
var top = ($('#bottom').position().top) + ($('#bottom').height());
这是jquery实际上使其比DOM已经提供的更加复杂的实例之一。
let { top, bottom, height, width, //etc } = $('#bottom')[0].getBoundingClientRect();
return top;
var bottom = $('#bottom').position().top+$('#bottom').offset().top+$('#bottom').outerHeight(true)