滚动多个元素/ DIV

时间:2014-11-20 12:05:20

标签: javascript jquery html css

我想同时滚动多个div。

我有一些有用的东西,但它在慢速机器(特别是手机)上表现不佳

<!-- HTML -->
<div class="container">
    <div class="row">
        <div class="scroller">
            <div>some really long content that just keeps going on and on and on and on and on and on and on and on and on and on and on and on and on</div>
        </div>
    </div>
    <div class="row">
        <div class="scroller">
            <div>some really long content that just keeps going on and on and on and on and on and on and on and on and on and on and on and on and on</div>
        </div>
    </div>
    <div class="row">
        <div class="scroller">
            <div>some really long content that just keeps going on and on and on and on and on and on and on and on and on and on and on and on and on</div>
        </div>
    </div>
    <div class="row">
        <div class="scroller">
            <div>some really long content that just keeps going on and on and on and on and on and on and on and on and on and on and on and on and on</div>
        </div>
    </div>
    <div class="row">
        <div class="scroller">
            <div>some really long content that just keeps going on and on and on and on and on and on and on and on and on and on and on and on and on</div>
        </div>
    </div>
</div>
<style>
/* CSS */
    .container { width:300px; }
    .scroller { width:100%; height:40px; padding:0 0 16px; line-height:40px; overflow-x:auto; overflow-y:hidden; white-space:nowrap; }
</style>

<script>
// jQuery
$(".scroller").scroll(function(){
    $(".scroller").scrollLeft($(this).scrollLeft());
});
</script>

Here's a pen/demo

我可以看到,无论我滚动一个元素,它滚动同一个类的其他元素,但因为我已经设置了一个滚动的听众&#39;在该类上,该函数再次为每个其他元素触发,因为它们已使用scrollLeft方法滚动。

有没有人对如何改进这个有任何想法?

4 个答案:

答案 0 :(得分:2)

您可以使用以下代码段:{需要一些测试,不确定它是否处理所有情况}

$(".scroller").css('outline', 0).attr('tabindex' , -1).scroll(function(e){
    if (!$(this).is(':hover') && !$(this).is(':focus'))  return;
    $(".scroller").not(this).scrollLeft($(this).scrollLeft());
});

答案 1 :(得分:1)

您可以在调用scrollLeft()之前禁用所有元素的滚动处理程序,然后重新启用滚动处理程序。 这将阻止重复调用处理程序。

var scrollHandler = function(){
  var $scrollers = $(".scroller");
  $scrollers.off("scroll", scrollHandler);
  $scrollers.scrollLeft($(this).scrollLeft());
  setTimeout(function(){$scrollers.on("scroll", scrollHandler);}, 0);
}

$(".scroller").on("scroll", scrollHandler);

答案 2 :(得分:1)

你能简单地只滚动滚动位置不同的元素吗?

$(".scroller").on('scroll', function(event){
  var a = $(this).scrollLeft();
  $(".scroller").each(function(){
    var b = $(this).scrollLeft();
    if(a !== b){
      $(this).scrollLeft(a);
    }
  });
});

答案 3 :(得分:0)

我认为最大的问题是,您将事件侦听器附加的元素上的scroll事件触发到事件侦听器中。如果将它从要滚动的元素中排除,则应该在低硬件上获得很大的性能提升:

$(".scroller").scroll(function(e){
    $(".scroller").not(this).scrollLeft($(this).scrollLeft());
});