JavaScript实现两个滚动条同步滚动

实现同步代码,这是一个横向滚动条的,纵向的直接修改监听的滚动条scrollLeft为scrollTop

 // 给滚动条设置监听事件
    setScrollRule() {
    
    
        let that = this; // 存一份this便于取用
        // 这里是使用的封装的表格组件,获取bodyWrapper
        this.one = this.$refs.one.$refs.multipleTable.$refs.bodyWrapper;
        this.two = this.$refs.two.$refs.multipleTable.$refs.bodyWrapper;
        // 2. 绑定滚动事件,顺带加上一个节流函数,也算是性能优化
        this.one.addEventListener(
          "scroll",
          _.throttle(
            function () {
    
    
              that.fn1(); // 50毫秒触发一次吧
            },
            10,
            {
    
    
              leading: true, //指定调用在节流开始前
              trailing: false, //指定调用在节流结束后,
            }
          )
        );
        // 同上...
        this.two.addEventListener(
          "scroll",
          _.throttle(
            function () {
    
    
              that.fn2();
            },
            10,
            {
    
    
              leading: true,
              trailing: false,
            }
          )
        );
    },
    // 3. 通过Element.scrollLeft属性 可以读取或设置元素滚动条到元素左边的距离
    fn1() {
    
    
      this.two.scrollLeft = this.one.scrollLeft;

      setTimeout(() => {
    
    
        this.two.scrollLeft = this.one.scrollLeft;
      }, 10);
    },
    // 同上...
    fn2() {
    
    
      this.one.scrollLeft = this.two.scrollLeft;
      setTimeout(() => {
    
    
        this.one.scrollLeft = this.two.scrollLeft;
      }, 10);
    },

需要引入的节流函数

import _ from "lodash";

结束后移除监听时间

 // 移除事件监听
        this.one.removeEventListener("scroll", this.fn1);
        this.two.removeEventListener("scroll", this.fn2);

猜你喜欢

转载自blog.csdn.net/qq_41180882/article/details/131916231
今日推荐