简体   繁体   English

如果当前滚动位置在底部附近,则javascript滚动到div的底部

[英]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. 我正在编写一个脚本,该脚本将使用溢出滚动将文本(大小变化)附加到div块(高度变化)。 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. 附加此文本后,我需要将div块滚动到底部才能看到新的附加文本,但是,如果当前滚动位置大约是底部滚动的10%左右,我只需要滚动到底部,否则在查看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 div.scrollTop + lineheight> scrollHeight

Like this? 像这样?

You just need to check to see if scrollTop is greater than 90% of the scrollHeight . 您只需要检查一下scrollTop是否大于scrollHeight 90%。

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

scrollHeight = scrollTop + clientHeight + [fudge factor] scrollHeight = scrollTop + clientHeight + [软键]

The "fudge factor" seems to be around 30-40 (pixels) for me. 对我来说,“忽悠系数”似乎约为30-40(像素)。 So try this: 所以试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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