如何镜像两个不同框的滚动

How do I mirror the scrolling of two deferent boxes

我有两个内容相同但尺寸不同的盒子,我在它们之间同步滚动,所以如果你滚动一个,另一个就会跟着滚动,反之亦然,问题是一旦你向下滚动,它就会接缝继续滚动就其本身而言,有什么办法可以解决这个问题吗?

代码笔:https://codepen.io/rgbskills/pen/JjrRpVN?editors=0010

let master = document.getElementById('text');
let slave = document.getElementById('text2');

const masterScrollHeight = master.scrollHeight;
const masterClientHeight = master.clientHeight;
const masterHeight = masterScrollHeight - masterClientHeight;

const slaveScrollHeight = slave.scrollHeight;
const slaveClientHeight = slave.clientHeight;
const slaveHeight = slaveScrollHeight - slaveClientHeight;


const handleScrollMaster = (e) => {
  const newMasterScrollTop = e.currentTarget.scrollTop;
  const percentageMasterDone = newMasterScrollTop / masterHeight;
  const newSlaveScrollTop = Math.ceil(percentageMasterDone * slaveHeight);
  
  slave.scroll({
    top: newSlaveScrollTop
  })
}

const handleScrollSlave = (e) => {
  
  const newSlaveScrollTop = e.currentTarget.scrollTop;
  const percentageSlaveDone = newSlaveScrollTop / slaveHeight;
  const newMasterScrollTop = Math.ceil(percentageSlaveDone * masterHeight);
  
  master.scroll({
    top: newMasterScrollTop
  })
}

master.addEventListener("scroll", handleScrollMaster);
slave.addEventListener("scroll", handleScrollSlave);

我不确定为什么这能解决我的问题,但这是我的解决方案:

我只是从事件侦听器功能之一中删除了 Math.ceil

代码笔:https://codepen.io/rgbskills/pen/JjrRpVN?editors=0010

let master = document.getElementById('text');
let slave = document.getElementById('text2');

const masterScrollHeight = master.scrollHeight;
const masterClientHeight = master.clientHeight;
const masterHeight = masterScrollHeight - masterClientHeight;

const slaveScrollHeight = slave.scrollHeight;
const slaveClientHeight = slave.clientHeight;
const slaveHeight = slaveScrollHeight - slaveClientHeight;


const handleScrollMaster = (e) => {
  const newMasterScrollTop = e.currentTarget.scrollTop;
  const percentageMasterDone = newMasterScrollTop / masterHeight;
  const newSlaveScrollTop = Math.ceil(percentageMasterDone * slaveHeight);
  slave.scroll({
    top: newSlaveScrollTop
  })
}

const handleScrollSlave = (e) => {
  const newSlaveScrollTop = e.currentTarget.scrollTop;
  const percentageSlaveDone = newSlaveScrollTop / slaveHeight;
  // for some reason if I apply Math.ceil here it will cause an infinite scroll
  const newMasterScrollTop = percentageSlaveDone * masterHeight;
  
  master.scroll({
    top: newMasterScrollTop
  })
}

master.addEventListener("scroll", handleScrollMaster);
slave.addEventListener("scroll", handleScrollSlave);