开发者

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

开发者 https://www.devze.com 2023-04-07 11:06 出处:网络
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

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) {
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消