Javascript 仅当用户在DOM操作之前已经在页面底部时,才滚动到页面底部
我想学习如何使用Javascript 仅当用户在DOM操作之前已经在页面底部时,才滚动到页面底部,javascript,jquery,Javascript,Jquery,我想学习如何使用window.scrollTo 以下是所需的行为: 确定是将用户滚动到页面底部,还是看不到滚动条 然后我想发展一个部门,这是可行的 如果#1为真,使用window.scrollTo在DIV增大后滚动到页面底部,从而改变窗口高度 想法 测试用例:根据Han的想法,我们可以检测窗口是否像这样滚动到底部: $('button').click(function(){ var shouldScroll = $(document).scrollTop() + $(window).he
window.scrollTo
以下是所需的行为:
window.scrollTo
在DIV增大后滚动到页面底部,从而改变窗口高度测试用例:根据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);
}
});
$(“按钮”)。单击(函数(){
var shouldScroll=$(文档).scrollTop()+$(窗口).height()===$(文档).height();
$('added content')。appendTo('body');
如果(应滚动){
$(窗口).scrollTop(document.body.scrollHeight);
}
});
这里更新了JSFIDLE:首先,您必须检查是否位于页面底部。使用Gaby的答案,我得到:
这并不能检查用户在修改DOM之前是否在页面底部。我想他需要帮助的只是#3。
$('button').click(function(){
var shouldScroll = $(document).scrollTop() + $(window).height() === $(document).height();
$('<div>added content</div>').appendTo('body');
if(shouldScroll) {
$(window).scrollTop(document.body.scrollHeight);
}
});
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;
}
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;