注意PC端中没有触摸事件,下面用局部指令
移动端拖拽
directives:{
drag:{
inserted(el,binding){
el.style.position = 'absolute'
let x = 0
let y = 0
el.ontouchstart = function(es) {
x = es.touches[0].pageX - el.offsetLeft
y = es.touches[0].pageY - el.offsetTop
document.ontouchmove = function(ev) {
let left = ev.touches[0].pageX - x
let top = ev.touches[0].pageY - y
el.style.left = left + 'px'
el.style.top = top + 'px'
}
}
el.ontouchend = function() {
document.ontouchmove = null
}
}
}
}
PC端拖拽
directives:{
drag:{
inserted(el,binding){
let x = 0
let y = 0
el.style.position = 'absolute'
el.onmousedown = function(ed) {
x = ed.clientX - el.offsetLeft
y = ed.clientY - el.offsetTop
document.onmousemove = function(ev) {
let left = ev.clientX - x
let top = ev.clientY - y
el.style.left = left + 'px'
el.style.top = top + 'px'
}
}
el.onmouseup = function() {
document.onmousemove = null
}
}
}
}
下面是一个拖拽小案例
Vue.directive('drag', {
inserted: function (el) {
let arr = JSON.parse(localStorage.getItem('position')) || [{
x:(document.getElementById('app').scrollWidth-450)/2 + 'px',
y:(document.getElementById('app').scrollHeight-250)/2 + 'px'
}]
el.style.left=arr[0].x
el.style.top=arr[0].y
el.onmousedown=function(ev){
var x=ev.clientX-el.offsetLeft;
var y=ev.clientY-el.offsetTop;
document.onmousemove=function(ev){
var left=ev.clientX-x;
var top=ev.clientY-y;
el.style.left=left+'px';
el.style.top=top+'px';
};
el.onmouseup=function(){
document.onmousemove = null
arr.unshift({x:el.style.left,y:el.style.top})
if(arr.length > 1) {
arr.length = 1
}
localStorage.setItem('position',JSON.stringify(arr))
};
};
}
})