vue中引入mousedown事件和document的mousemove事件模拟table滚动条

    vue项目中需要模拟表格的滚动条效果,涉及的事件就是mousedown、mouseup、mousemove;其中mousedown事件是绑定在滚动条上的,但是mousemove和mouseup事件则应该是绑定在document上,这样才能很好地实现滚动条的拖动;

  首先在组件methods中定义两个函数:

1、获取鼠标位置坐标:

  getPos(ev){
          let scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
          let scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft;
         return {x: ev.clientX+scrollLeft, y: ev.clientY+scrollTop};
       }
2、定义滚动条的mousedown事件,并在其内部定义document的mousemove和mouseup事件:

    drag(ev){
        this.slider.className ='focus';
        let that = this;
        let scale =  this.wrapDiv.clientHeight /  this.contentDiv.clientHeight;/*确定滚动比例*/
        let oEvent = ev || event;
        let pos = that.getPos(oEvent); //获取鼠标坐标
        this.disY = pos.y - this.slider.offsetTop;
        this.disX = pos.x - this.slider.offsetLeft;
        document.onmousemove =function (ev) { /*注册document的mousemove事件*/
          let oEvent = ev || event;
          let pos = that.getPos(oEvent);
          let t = pos.y - that.disY;
          t = (t<0) ?0:t;/*限定滚动范围*/
          if (t > that.sliderWrap.clientHeight - that.slider.offsetHeight) {
            t = that.sliderWrap.clientHeight - that.slider.offsetHeight;
          }
          that.slider.style.top=t+'px';/*设置滚动条位置*/
          let t1 = -(t+1)/scale;
          that.contentDiv.style.top = t1 + "px";/*表格内容按比例滚动*/
          that.contentDiv1.style.top = t1 + "px";
          };
        document.onmouseup = function () {/*鼠标放开清除事件*/
          that.slider.className ='';
          document.onmousemove = null;
          document.onmouseup = null;
        };
        return false;//兼容firefox
      },
      initScroll(){
        this.slider.style.top = 0;
        this.contentDiv.style.top = 0;
        this.contentDiv1.style.top = 0;
      },
3、最后在滚动条元素上绑定mousedown事件即可:
  <div id="sliderWrap">
      <div id="slider" @mousedown = drag($event)></div>
  </div>



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值