简体   繁体   中英

Autoscroll to bottom of DIV after updating, only if already at bottom of DIV before update

The code below adds content to a DIV and then scrolls it to show the new content:

<div id="Scrollable" style="height:400px; overflow:scroll;>
1<br />
2<br />
3<br />
4<br />
</div>

<script>
// Should DIV be auto scrolled?
var autoScroll = true;

// Add new content
$('#Scrollable').append('5<br />6<br />');

if ( autoScroll ){ // Scroll to bottom of DIV
    $('#Scrollable').animate({ scrollTop: $('#Scrollable').prop('scrollHeight') });
}
</script>

What I need is a check at the var autoScroll = true stage to detect whether or not the DIV is currently scrolled to the bottom. So that after the new content is added, it will only autoscroll if the DIV was at the bottom before.

What problems did you encounter when trying to write this? Here's a jsFiddle example, based off the first result I found in Google for "jquery check if div is scrolled to bottom". It seems to work fine.

http://jsfiddle.net/QB75Z/

And here's a link to the article I found: http://www.yelotofu.com/2008/10/jquery-how-to-tell-if-youre-scroll-to-bottom/

EDIT : Here's the actual code from the jsFiddle I posted, in case someone's searching and jsFiddle disappears. Have a scrollable div (give it a height and overflow-y: scroll ) with an id of scrollable, and an inner div inside that with a class of inner. Then you can determine whether the div is scrolled to the bottom or not by using the following code:

var scrollable = $('#scrollable');
var inner = $('#scrollable > .inner');

// check if div is scrolled to bottom before addition of new content
var atBottom = Math.abs(inner.offset().top) + scrollable.height() + scrollable.offset().top >= inner.outerHeight();

// add additional content to .inner here

if ( atBottom ) {
  // do stuff like scroll to bottom etc
}

There's a good example of this listed here .

The following equivalence returns true if an element is at the end of its scroll, false if it isn't.

element.scrollHeight - element.scrollTop === element.clientHeight

The demo listed on that page is very helpful as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM