【发布时间】:2010-12-25 20:21:22
【问题描述】:
如何使用 jquery 向下滚动到 iframe 或页面的底部?
【问题讨论】:
如何使用 jquery 向下滚动到 iframe 或页面的底部?
【问题讨论】:
如果您想要一个不错的慢速动画滚动,对于任何带有href="#bottom" 的锚点,这会将您滚动到底部:
$("a[href='#bottom']").click(function() {
$("html, body").animate({ scrollTop: $(document).height() }, "slow");
return false;
});
随意更改选择器。
【讨论】:
scrollTop() 返回从可滚动区域的视图中隐藏的像素数,因此给它:
$(document).height()
实际上会超出页面底部。为了使滚动真正“停止”在页面底部,需要减去浏览器窗口的当前高度。如果需要,这将允许使用缓动,所以它变成:
$('html, body').animate({
scrollTop: $(document).height()-$(window).height()},
1400,
"easeOutQuint"
);
【讨论】:
easeOutQuint需要插件,jQuery本身只有linear和swing。
<!DOCTYPE html>,Chrome 将返回完全相同的窗口和文档高度值,在这种情况下,$(document).height()-$(window).height() 将始终返回 0。请参阅此处:stackoverflow.com/questions/12103208/…
例如:
$('html, body').scrollTop($(document).height());
【讨论】:
在此线程无法满足我的特定需求(在特定元素内滚动,在我的情况下为 textarea)之后,我发现了这一点,这可能对阅读此讨论的其他人有所帮助:
因为我已经有了我的 jQuery 对象的缓存版本(下面代码中的 myPanel 是 jQuery 对象),我添加到我的事件处理程序的代码就是这样:
myPanel.scrollTop(myPanel[0].scrollHeight - myPanel.height());
(感谢本)
【讨论】:
var d = $('#mydiv'); d.scrollTop (d[0].scrollHeight - d.height ());
跳转(立即滚动)到整个页面底部的简单函数。它使用内置的.scrollTop()。我没有尝试将其调整为适用于单个页面元素。
function jumpToPageBottom() {
$('html, body').scrollTop( $(document).height() - $(window).height() );
}
【讨论】:
$(document).scrollTop($(document).height()); 解决了这个问题
如果您不关心动画,那么您不必获取元素的高度。至少在我尝试过的所有浏览器中,如果你给scrollTop 一个大于最大值的数字,它只会滚动到底部。所以给它尽可能大的数字:
$(myScrollingElement).scrollTop(Number.MAX_SAFE_INTEGER);
如果你想滚动页面,而不是带有滚动条的元素,只需让myScrollingElement 等于'body, html'。
由于我需要在几个地方这样做,所以我编写了一个快速而肮脏的 jQuery 函数以使其更方便,如下所示:
(function($) {
$.fn.scrollToBottom = function() {
return this.each(function (i, element) {
$(element).scrollTop(Number.MAX_SAFE_INTEGER);
});
};
}(jQuery));
所以当我附加一堆东西时我可以这样做:
$(myScrollingElement).append(lotsOfHtml).scrollToBottom();
【讨论】:
这个对我有用:
var elem = $('#box');
if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {
// We're at the bottom.
}
【讨论】:
之前回答中提到的脚本,比如:
$("body, html").animate({
scrollTop: $(document).height()
}, 400)
或
$(window).scrollTop($(document).height());
在 Chrome 中不起作用,并且在 Safari 中会跳动 以防 html 标签在 CSS 有 overflow: auto; 属性集。我花了将近一个小时才弄清楚。
【讨论】:
$('.block').scrollTop($('.block')[0].scrollHeight);
当新消息到达时,我使用此代码滚动聊天。
【讨论】: