还可以封装一下代码,不想封了,移动端pc端区别:事件不同,pc端鼠标事件移动端触摸事件;pc端直接获取e.pageX,移动端e.changedTouches[0].pageX
使用直接在dom绑定v-drag
directives: { drag(el, bindings, vnode) { let phone = false let max = max || 0 if(window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) { phone = true; // 移动端 } let scaleRates = scaleRates || 1 // dom缩放比例 特殊需求预留位置 // 移动端 if(phone){ el.ontouchstart = function (e) { if(bindings.value.cantChange !== true){ bindings.value.style['z-index'] = max + 1 } // 不能操作 if(bindings.value.isClock === true || bindings.value.operate === false){ return } var disx = (e.changedTouches[0].pageX / scaleRates) - el.offsetLeft var disy = (e.changedTouches[0].pageY / scaleRates) - el.offsetTop const move = (e) => { el.style.left = ((e.pageX / scaleRates) - disx) + 'px' el.style.top = ((e.pageY / scaleRates) - disy) + 'px' bindings.value.style.left = ((e.changedTouches[0].pageX / scaleRates) - disx) + 'px' bindings.value.style.top = ((e.changedTouches[0].pageY / scaleRates) - disy) + 'px' } document.ontouchmove = function(e){ move(e) } const up = (e) => { document.ontouchmove = document.ontouchend = null } document.ontouchend = function (e) { up(e) } } } // pc端 else{ el.onmousedown = function (e) { if(bindings.value.cantChange !== true){ bindings.value.style['z-index'] = max + 1 } // 不能操作 if(bindings.value.isClock === true || bindings.value.operate === false){ return } var disx = (e.pageX / scaleRates) - el.offsetLeft var disy = (e.pageY / scaleRates) - el.offsetTop const move = (e) => { el.style.left = ((e.pageX / scaleRates) - disx) + 'px' el.style.top = ((e.pageY / scaleRates) - disy) + 'px' bindings.value.style.left = ((e.pageX / scaleRates) - disx) + 'px' bindings.value.style.top = ((e.pageY / scaleRates) - disy) + 'px' } document.onmousemove = function(e){ move(e) } const up = (e) => { document.onmousemove = document.onmouseup = null } document.onmouseup = function (e) { up(e) } } } } },
标签:el,style,vue,dom,px,value,scaleRates,bindings,拖拽 From: https://www.cnblogs.com/myqinyh/p/17393694.html