本文实例为大家分享了Vue实现简单拖拽效果的具体代码,供大家参考,具体内容如下
自定义指令v-drag
l 存在时 只能横向拖拽
t 存在时 只能纵向拖拽
lt都存在时 可以任意方向拖拽
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < meta http-equiv = "X-UA-Compatible" content = "ie=edge" > < title >拖拽</ title > < style > *{ margin: 0; padding: 0; } #box{ background: red; width: 100px; height: 100px; position: absolute; } </ style > < script src = "vue.js" ></ script > </ head > < body > < div id = "app" > < div id = "box" v-drag.l.t = "flag" ></ div > </ div > < script > Vue.directive("drag",(el,{modifiers,value})=>{ let{l,t}=modifiers; el.addEventListener("mousedown",handleDownCb) let disX,disY; function handleDownCb(e){ disX=e.offsetX; disY=e.offsetY; // console.log(disX,disY) document.addEventListener("mousemove",handleMoveCb); document.addEventListener("mouseup",handleUpCb); } function handleMoveCb(e){ let x=e.clientX-disX; let y=e.clientY-disY; if((l&&t) && value){ el.style.left=x+"px"; el.style.top=y+"px"; return; } if(l&&value){ el.style.left=x+"px"; return; } if(t&&value){ el.style.top=y+"px"; return; } } function handleUpCb(){ document.removeEventListener("mousemove",handleMoveCb); document.removeEventListener("mouseup",handleUpCb); } }) let vm=new Vue({ el:"#app", data:{ flag:true } }) </ script > </ body > </ html > |
注:
改变v-drag.l v-drag.t v-drag.l.t 即可实现横向 纵向 任意方向的拖拽
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_45092792/article/details/97130208