如何使用jQuery和.on让两个滚动条同时滚动

How can I get two scroll bars to scroll at the same time with jQuery and .on?

本文关键字:两个 滚动条 滚动 jQuery 何使用 on      更新时间:2023-10-26

我有一个建议将其添加到我的代码中:

<script type="text/javascript">
    $(document).on('scroll', '.wrapper1', function () {
        $(".wrapper2").scrollLeft($(".wrapper1").scrollLeft());
    });
    $(document).on('scroll', '.wrapper2', function () {
        $(".wrapper1").scrollLeft($(".wrapper2").scrollLeft());
    });
</script>

所以我可以同时更改两个滚动条。这是我正在使用的HTML:

<div class="wrapper1">
   <div class="div1">
   </div>
</div>
<div class="wrapper2">
   <div class="div2">
      <div data-ng-class="{'hidden': loading!=0 }"
         data-ng-form="gridForm">
         <table class="form grid table" style="height: 600px; width: 1500px;">
         </table>
      </div>
   </div>
</div>

我已经加载了jQuery,但滚动条似乎没有一起滚动。有人能帮我解释一下为什么会这样吗?

注意,我需要使用.on,因为滚动条区域是动态加载的。

这是一把小提琴:http://jsfiddle.net/npwD8/

我已经将您在JSFiddle上的示例更新为有效的示例,尽管我不确定它最终是否适合您的用例。

http://jsfiddle.net/npwD8/4/

$('.wrapper').on('scroll', function({
    $(".wrapper").not(this).scrollLeft($(this).scrollLeft());
});

滚动事件不会冒泡,因此从窗口向下委派不会起作用。当这些元素被添加到DOM中时,您需要手动处理这些事件的附件。

scroll()事件不符合使用事件冒泡的条件;

"在所有浏览器中,loadscrollerror事件(例如,在<img>上元素)不起泡。"-jQuery on()文档.

因此,事件委派(例如$(document).on('...', '...'))恐怕是不可能的。