用vue指令实现一个拖拽功能

注意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))
    };
   };
  }
})

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值