暂停自动滚动Div

Pause Auto-scrolling Div

本文关键字:Div 滚动 暂停      更新时间:2023-09-26

我有一个div,我想在页面加载时上下滚动,一旦用户悬停在div上就暂停滚动。我已经设法让div上下滚动,但是我不能让它暂停。

有什么建议吗?

 <div id="box" class="timeline container" style="overflow:scroll; width:100%; height:300px;">
    //CONTENT
 </div>         
 <script>
    $("#box").animate({ scrollTop: $(document).height() }, 4000);
    setTimeout(function() {
     $('#box').animate({scrollTop:0}, 4000); 
    },4000);
    setInterval(function(){
    $("#box").animate({ scrollTop: $(document).height() }, 4000);
    setTimeout(function() {
    $('#box').animate({scrollTop:0}, 4000); 
    },4000);
    },8000);

 </script>

我建议你不要使用动画的滚动功能。相反,只需每100毫秒(或任何时间)增加滚动位置。

您还需要添加标志来确定滚动方向和暂停状态:

// global level variables.
var isPaused = false;
var direction = 1;
var element = $('#box');
// interval for scroll.
setInterval(function () {
    if(!isPaused){
        var pos = element.scrollTop();
        var offset = 1 * direction;
        element.scrollTop(pos + offset);
        // Change the scroll direction when hit an end.
        if ((element[0].scrollHeight - element.scrollTop() == element.outerHeight()) || (element.scrollTop() <= 0)) {
            direction *= -1;
        }
    }
}, 100);

然后你可以在mouseenter和mouseexit事件时改变isPaused标志,或者使用JQuery hover事件:

$('#box').hover(
  function() {
    isPaused = true;
  }, function() {
    isPaused = false;
  }
);

下面是一个工作示例

你应该能够停止/暂停你的动画与jQuery函数stop(): https://api.jquery.com/stop/