滚动停止时jQuery检测。

时间:2018-04-27 14:39:17

标签: jquery

我在这里有一个简单的演示,我有两个独立的滚动容器。

我正在使用jQuery将滚动从一个容器复制到另一个容器,所以当滚动一个容器时,另一个容器也会这样做。

这可能是生涩的,有时每个容器中的元素都不对齐。

如果我能检测到滚动停止的时间,我想我可以确保每个滚动左侧都是相同的。

我如何能够检测滚动何时停止,以便我可以在每个容器上设置scrollLeft。

-- Or in a form closer to Daniel Wagner's answer
func str = fmap digitToInt (filter (< 'a') str)
  $('.scroll-top').on('scroll', function() {
    var val = $(this).scrollLeft();
    $('.scroll-bottom').scrollLeft(val);
  });

$('.scroll-bottom').on('scroll', function() {
    var val = $(this).scrollLeft();
    $('.scroll-top').scrollLeft(val);
  });
.wrapper{
  border: 2px solid grey;
  padding: 5px;
  width: 500px;
  margin: 0 auto;
}

.scroll-top,
.scroll-bottom{
  overflow-y: scroll;
}

.content{
  display: flex;
  width: 1000px;
  height: 100px;
}

.content .block{
    background: red;
    width: 50px;
    height: 100px;
    margin-right: 10px;
}  

.content-top{
  margin-bottom: 2px;
}

.scroll::-webkit-scrollbar { 
  display: none;
}

.scroll { 
  -ms-overflow-style: none; 
}

1 个答案:

答案 0 :(得分:1)

您可以使用settimeout,以便动画最后只触发一次:

var timeoutVar;
$('.scroll-bottom').on('scroll', function() {
    var $this = $(this);
    clearTimeout(timeoutVar);  // clear timeout so it is not fired if still scrolling
    timeoutVar = setTimeout(function() {
      var val = $this.scrollLeft();
      $('.scroll-top').scrollLeft(val);
    }, 100); // 100ms should be long enough so that this will only be fired after the scroll has finished
  });
相关问题