我想了解如何使用window.scrollTo
。只有当用户在DOM操作之前已经在底部时才滚动到页面底部
这里的是所期望的行为:
- 确定用户是否被滚动到页面底部,或没有滚动条可见
- 然后我想长出了DIV,这是工作
- 如果#1为真,则使用
window.scrollTo
在DIV生长后更改窗口高度后滚动到页面的底部。
想法?
我想了解如何使用window.scrollTo
。只有当用户在DOM操作之前已经在底部时才滚动到页面底部
这里的是所期望的行为:
window.scrollTo
在DIV生长后更改窗口高度后滚动到页面的底部。想法?
$(window).scrollTop(document.body.scrollHeight);
从汉的想法工作,我们可以通过检测窗口是否滚动至底部是这样的:
$('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/
首先,你必须检查你是否在页面的底部。使用盖比的回答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;
}
接下来,你可以操纵的DOM,并滚动至底部,如果通过scrollbarAtBottom
返回的值是true
:
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;
这不检查用户是否在DOM被修改之前,它在页面的底部。 – 2010-11-30 23:49:15