我想学习如何使用window.scrollTo
。
这是所需的行为:
window.scrollTo
滚动到页面底部,这会改变窗口高度。想法?
答案 0 :(得分:2)
根据Han的想法,我们可以检测窗口是否像这样滚动到底部:
$('button').click(function(){
var shouldScroll = $(document).scrollTop() + $(window).height() === $(document).height();
$('<div>added content</div>').appendTo('body');
if(shouldScroll) {
$(window).scrollTop(document.body.scrollHeight);
}
});
在此处更新了jsFiddle:http://jsfiddle.net/JamesKovacs/nQntc/1/
答案 1 :(得分:0)
首先,您必须检查是否位于页面底部。使用Gaby对Determining when scrolled to bottom of a page with Javascript的回答我得到了:
function scrollbarAtBottom() {
var totalHeight, currentScroll, visibleHeight;
if (document.documentElement.scrollTop)
currentScroll = document.documentElement.scrollTop;
else
currentScroll = document.body.scrollTop;
totalHeight = document.body.offsetHeight;
visibleHeight = document.documentElement.clientHeight;
if (totalHeight <= currentScroll + visibleHeight)
return true;
else
return false;
}
接下来,如果scrollbarAtBottom
返回的值为true
,您可以操纵DOM并滚动到底部:
var atBottom = scrollbarAtBottom();
/* do some stuff */
if (atBottom)
if (document.documentElement.scrollTop)
document.documentElement.scrollTop = document.documentElement.clientHeight;
else
document.body.scrollTop = document.body.clientHeight;
答案 2 :(得分:-1)
$(window).scrollTop(document.body.scrollHeight);