javascript - dom 元素上的滚动冲突

标签 javascript dom scroll

我的演示中有两个 div,我想滚动不同的 div,但不能同时滚动两个。

我已经写了console.log('left');和 console.log('左'); 。 当我只需要向左滚动或向右滚动时,这似乎是冲突。

我得到了 hsz 的答复,但我的问题似乎很难澄清:(

// console:left
        document.getElementById('body').onscroll = function (e) {
            document.getElementById('num').scrollTop = document.get`enter code here`ElementById('body').scrollTop;
            console.log('left');

        }


// console:right
        document.getElementById('num').onscroll = function (e) {
            document.getElementById('body').scrollTop = document.getElementById('num').scrollTop;
            console.log('right');

        }

https://codepen.io/AsheLi/pen/djexyE?editors=1111

最佳答案

您必须引入一个标志来指定初始化滚动的内容 - 有机滚动(用户完成的当前滚动)或第二个 div:

let organicScrolling = true;

// console:left
document.getElementById('body').onscroll = function(e) {
  if (organicScrolling) {
    document.getElementById('num').scrollTop = document.getElementById('body').scrollTop;
    console.log('left');
  }
  organicScrolling = !organicScrolling;
};

// console:right
document.getElementById('num').onscroll = function(e) {
  if (organicScrolling) {
    document.getElementById('body').scrollTop = document.getElementById('num').scrollTop;
    console.log('right');
  }
  organicScrolling = !organicScrolling;
};

demo

关于javascript - dom 元素上的滚动冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51667578/

相关文章:

javascript - 长时间运行函数的 DOM 刷新

html - 子 div 是可滚动的,但在子内添加内容时 body 的高度仍然增加

javascript - 在父 div 上滚动的同时滚动子 div

javascript - 从 CSS 模块中访问全局类

javascript - nvd3 : set background fill behind line chart

javascript - 如何在 JavaScript 中模拟宏?

javascript - 我不断收到 [$injector :modulerr] in angularJS

php - 从 jquery 对象数组设置值 php?

Jquery如何向dom添加元素

javascript - 如果有办法做 background-size : cover and still be able to scroll around the image