問題描述
滾動到頁面底部,僅當用戶在 DOM 操作之前已經位於底部時 (Scroll to bottom of page, only if the user already was at the bottom before DOM manipulation)
I'd like to learn how to use window.scrollTo
.
Here's is the desired behavior:
- Determine if the user is scrolled to the bottom of the page, or no scroll bar is visible
- Then I want to grow a DIV, this is working
- If #1 was true, use
window.scrollTo
to scroll to the bottom of the page after the DIV has grown which changed the window height.
Ideas?
參考解法
方法 1:
Working from Han's idea, we can detect whether the window is scrolled to the bottom like this:
$('button').click(function(){
var shouldScroll = $(document).scrollTop() + $(window).height() === $(document).height();
$('<div>added content</div>').appendTo('body');
if(shouldScroll) {
$(window).scrollTop(document.body.scrollHeight);
}
});
Updated jsFiddle here: http://jsfiddle.net/JamesKovacs/nQntc/1/
方法 2:
First, you'll have to check whether you're at the bottom of the page or not. Using Gaby's answer to Determining when scrolled to bottom of a page with Javascript I get:
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;
}
Next, you can manipulate the DOM and scroll to the bottom if the value returned by scrollbarAtBottom
was 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;
(by AnApprentice、James Kovacs、Marcel Korpel)