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

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

1、获取鼠标位置坐标:

1
2
3
4
5
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事件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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事件即可:

1
2
3
<div id="sliderWrap">
<div id="slider" @mousedown = drag($event)></div>
</div>