简体   繁体   中英

javascript scroll to bottom of div if current scroll location is near bottom

I am working on a script that will append text (varies on size) to a div block (varies in height) with overflow scroll. After this text is appended I need the div block to be scrolled to the bottom in order to see the new appended text, however I need it only to scroll to the bottom if the current scroll position is around 10% of scroll close to the bottom, otherwise it would be annoying if it scrolled down while viewing the top portion of the div.

This is what I came up with, it is run after text is appended:

var divblock = document.getElementById('div'); //the block content is appended to
var divheight = divblock.offsetHeight;//get the height of the divblock
//now check if the scroller is near the bottom and if it is then scroll the div to the abslute bottom

if (***HELP HERE***) divblock.scrollTop=divblock.scrollHeight; ///scroll to bottom

much appreciated thanks!

if( divblock.scrollTop < divblock.scrollHeight )

div.scrollTop + lineheight > scrollHeight

Like this?

You just need to check to see if scrollTop is greater than 90% of the scrollHeight .

if (divblock.scrollTop > divblock.scrollHeight*0.9) {
  divblock.scrollTop=divblock.scrollHeight; 
}

scrollHeight = scrollTop + clientHeight + [fudge factor]

The "fudge factor" seems to be around 30-40 (pixels) for me. So try this:

if ((divblock.scrollTop + divblock.clientHeight + 50) > divblock.scrollHeight) {
    ...
}

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