前言
在最近的项目中,登录需要用到滑动验证,网上有很多第三方可以集成,但是项目没那么着急,出于学习的目的,打算自己写一个组件。最终效果: 
开发思路
1、为了兼容移动端,需要用到mouse和touch事件; 2、在鼠标按下时添加监听事件:mousemove、touchmove、mouseup、touchend; 3、在鼠标移动时,获取当前位置,赋值给某个变量,用来控制滑块css的left值;(或者改用transform的translateX) 4、在鼠标弹起时,验证是否正确;
一、画出元素
js
<div class="容器样式">
<div class="底图样式"><img :src="底图"></div>
<div class="滑块样式" @touchstart="onPointerDown($event)"
@mousedown="onPointerDown($event)" :style="{left:currentX+'px'}">
移动
</div>
</div>1
2
3
4
5
6
7
2
3
4
5
6
7
二、绑定事件
其中on、off是自定义工具,用于添加事件和销毁事件
js
export default {
data () {
return {
currentX: 0,
startX:0,
};
},
methods: {
// 获取当前X轴坐标
getPointerX (e) {
let touch = Math.round(e.touches[0].clientX);
return e.type.indexOf('touch') !== -1 ? touch : Math.round(e.clientX);
},
/**
* 鼠标按下
* @param event
*/
onPointerDown (event) {
event.preventDefault();
this.startX = this.getPointerX(event);
on(window, 'mousemove', this.onPointerDrag);
on(window, 'touchmove', this.onPointerDrag);
on(window, 'mouseup', this.onPointerDragEnd);
on(window, 'touchend', this.onPointerDragEnd);
},
/**
* 拖拽中
* @param event
*/
onPointerDrag (event) {
let diff = this.getPointerX(event) - this.startX;
// 限定最大宽度,先写死
if (diff > 0 && diff < 280) {
this.currentX = diff;
}
},
/**
* 鼠标弹起
*/
onPointerDragEnd () {
this.requestResult();
off(window, 'mousemove', this.onPointerDrag);
off(window, 'touchmove', this.onPointerDrag);
off(window, 'mouseup', this.onPointerDragEnd);
off(window, 'touchend', this.onPointerDragEnd);
},
/**
* 验证
*/
requestResult(){
this.$axios.get(请求地址 + this.currentX).then(() => {
// TODO 成功
}).catch(() => {
// TODO 失败
});
}
}
};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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62