JSFiddle - React, Tailwind, and code Playground

by knightgao

HTML

<html>
  <div class="a" id=test1>
    <div class="b">1</div>
  </div>
  <div class="a" id=test2>
    <div class="b">1</div>
  </div>
  <div class="c" id=test3>
    <div class="b">1</div>
  </div>

 </html>

CSS

.a{
  background:red;
  height:100px;
  overflow:auto;
}

.c{
  background:red;
  height:100px;
  overflow:hidden;
}

.b{
  background:yellow;
  height:200px;
}

JavaScript

function ready() {
  const test1 = document.getElementById("test1")
  const test2 = document.getElementById("test2")
  const test3 = document.getElementById("test3")

  function syncScroller(nodes) {
    let max = nodes.length
    if (!max || max === 1) return
    let sign = 0; // 用于标注
    nodes.forEach((ele, index) => {
      ele.addEventListener('scroll', function() {
        window.requestAnimationFrame(() => {
          // 给每一个节点绑定 scroll 事件
          if (!sign) { // 标注为 0 时 表示开始滚动,触发同步
            sign = max - 1;
            let top = this.scrollTop
            let left = this.scrollLeft
            for (node of nodes) { // 同步所有除自己以外节点
              if (node === this) continue;
              console.log("同步")
              node.scrollTo(left, top);
            }
          } else
            --sign; // 其他节点滚动时 标注减一
        })
      }, {
        passive: true
      });
    });
  }

  syncScroller([test1, test2, test3])

}

document.addEventListener("DOMContentLoaded", ready);