【问题标题】:Typed.js - Keep div scrolled to bottom as div increases in size unless user interacts with scrollbar?Typed.js - 除非用户与滚动条交互,否则随着 div 大小的增加,保持 div 滚动到底部?
【发布时间】:2017-06-11 02:56:19
【问题描述】:

我正在使用 Typed.js 将文本行动态添加到 div。几秒钟后,固定高度的 div 会出现一个滚动条。我希望滚动条一直滚动到底部,因为不断添加内容而不编辑我的 Typed.js 库的代码。

我能够用代码完成这个:

window.setInterval(function() {
  var elem = document.getElementById('scrollBottom');
  elem.scrollTop = elem.scrollHeight;
}, 500);

但是,如果用户尝试向上滚动,代码显然会强制 div 滚动回底部。相反,我希望它允许用户随意滚动(但默认情况下,无需用户交互,滚动到底部)。

问题:每次添加新代码时,我都无法执行滚动;本质上,我不知道它什么时候会被添加。这就是我最初想到使用频繁间隔的原因(如上所示)。

如果用户点击了div的滚动条,有没有办法结束上述功能?

【问题讨论】:

    标签: javascript jquery html css scroll


    【解决方案1】:

    简单。像这样的:

        var youInterval; 
    
        function startInterval(){
    
            youInterval = setInterval(function() {
               var elem = document.getElementById('scrollBottom');
               elem.scrollTop = elem.scrollHeight;
            }, 500);
    
        }
    
        //If user scrolls, stop interval
        document.addEventListener('scroll', function (event) {
          if (event.target.id === 'scrollBottom') { // or any other filtering condition        
    
                clearInterval(youInterval);
          }
        }, true /*Capture event*/);
    
        //And start it whenever you need
        startInterval();
    

    【讨论】:

    • 工作就像一个魅力。非常感谢:)
    猜你喜欢
    • 2013-09-07
    • 2012-03-27
    • 2017-07-24
    • 1970-01-01
    • 2010-11-26
    • 2012-07-13
    • 2010-09-21
    相关资源
    最近更新 更多