首页 > 解决方案 > 使滚动条更新另一个滚动条,反之亦然

问题描述

鉴于以下js-bin,我该如何做到这一点,如果我在leftdiv 中滚动(使用鼠标滚轮)它将在rightdiv 中更新。

这可行,但是如果您取消注释代码,它将不再在鼠标滚轮处滚动 100 像素(默认 chrome 鼠标滚轮行为)。(它会逐像素滚动,这是我不想要的)。

基本上我需要保持默认的 chrome 鼠标滚轮滚动行为。

        const target = $("#target");
        $("#source").on("scroll", function (e) {
          e.preventDefault()
          target
            .prop("scrollTop", this.scrollTop)
            .prop("scrollLeft", this.scrollLeft);
       console.log("Called.")
        });
  
//    $("#target").on("scroll", function (e) {
//           e.preventDefault()
//           $("#source")
//             .prop("scrollTop", this.scrollTop)
//             .prop("scrollLeft", this.scrollLeft);
//        console.log("Called.")
//         });

标签: javascripthtmlcss

解决方案


使用 a等待Next TicksetTimeout()并修改您的代码,例如:

const $scrollers = $("#target, #source");
let tickTimeout = null;

$scrollers.on("scroll", function(e) {
  e.preventDefault();
  const self = this;
  const $other = $scrollers.not(self);

  clearTimeout(tickTimeout);
  tickTimeout = setTimeout(() => {
    $other.prop({
      scrollLeft: self.scrollLeft,
      scrollTop: self.scrollTop,
    });
  }, 0);
});
.scroll-example {
  display: inline-block;
  width: 40%;
  border: 1px solid black;
  margin-right: 20px;
  height: 100px;
  overflow-y: auto;
}
<p>Scroll the left div, watch the right one.</p>
<div id="target" class="scroll-example">
  1<br />2 <br />3 <br />4 <br />5 <br />6 <br />7 <br />8 <br />9 <br />10<br />11 <br />12 <br />13 <br />14 <br />15 <br />16 <br />17 <br />18<br />19 <br />20
</div>
<div id="source" class="scroll-example">
  1<br />2 <br />3 <br />4 <br />5 <br />6 <br />7 <br />8 <br />9 <br />10<br />11 <br />12 <br />13 <br />14 <br />15 <br />16 <br />17 <br />18<br />19 <br />20
</div>


<script src="https://code.jquery.com/jquery-3.5.1.js"></script>


推荐阅读