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

时间:2011-09-22 20:09:17

标签: javascript css html

我正在编写一个脚本,它将文本(大小不同)附加到div块(高度不同)和溢出滚动。在添加了这个文本之后,我需要将div块滚动到底部以便查看新的附加文本,但是如果当前滚动位置是靠近底部的滚动的大约10%,我只需要滚动到底部如果它在查看div的顶部时向下滚动会很烦人。

这就是我提出的,它是在附加文本后运行的:

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
非常感谢谢谢!

4 个答案:

答案 0 :(得分:0)

if( divblock.scrollTop < divblock.scrollHeight )

答案 1 :(得分:0)

div.scrollTop + lineheight&gt; scrollHeight属性

喜欢这个吗?

答案 2 :(得分:0)

您只需检查scrollTop是否大于scrollHeight的90%。

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

答案 3 :(得分:0)

scrollHeight = scrollTop + clientHeight + [fudge factor]

对我来说,“软糖因子”似乎在30-40(像素)左右。所以试试这个:

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