【发布时间】:2010-12-01 08:19:48
【问题描述】:
我想学习如何使用window.scrollTo。
这是所需的行为:
- 确定用户是滚动到页面底部,还是看不到滚动条
- 然后我想增长一个 DIV,这行得通
- 如果 #1 为真,则在 DIV 增长后使用
window.scrollTo滚动到页面底部,从而更改了窗口高度。
想法?
【问题讨论】:
标签: javascript jquery
我想学习如何使用window.scrollTo。
这是所需的行为:
window.scrollTo 滚动到页面底部,从而更改了窗口高度。想法?
【问题讨论】:
标签: javascript jquery
按照韩的思路,我们可以像这样检测窗口是否滚动到底部:
$('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/
【讨论】:
首先,您必须检查您是否位于页面底部。使用 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;
【讨论】:
$(window).scrollTop(document.body.scrollHeight);
【讨论】: