拖拽功能实现vue

1.按钮

<el-button
@mousedown="down" @touchstart="down" @mousemove="move"
@touchmove="move" @mouseup="end" @touchend="end" @touchcancel="end" >
</el-button>

2.检测平台,可以不检测

isMobile() {
        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)) {
          return false; // 移动端
        } else {
          return true; // PC端
        }
      }

3.js代码

 down(e) {
        this.flags = true
        let styleLoc = this.moveBtn.getBoundingClientRect()
        this.ispc = this.browserRedirect()
        let clientX = this.ispc === 'pc' ? e.clientX : e.targetTouches[0].clientX
        let clientY = this.ispc === 'pc' ? e.clientY : e.targetTouches[0].clientY
        this.disMove = [
          styleLoc.left - clientX,
          styleLoc.top - clientY,
        ]
      },
      move(e) {
        if (this.flags) {
          let clientX = this.ispc === 'pc' ? e.clientX : e.targetTouches[0].clientX
          let clientY = this.ispc === 'pc' ? e.clientY : e.targetTouches[0].clientY
          this.moveBtn.style.left = clientX + this.disMove[0] + 'px'
          this.moveBtn.style.top = clientY + this.disMove[1] + 'px'
        }
      },
      //鼠标释放时候的函数
      end() {
        this.flags = false
        document.addEventListener('touchmove', this.handler, {
          passive: false,
        })
      },
      handler(e) {
        if (this.flags) {
          event.preventDefault()
        } else {
          return true
        }
      },

问题

mousemove并非逐帧监听,而是大概10-20毫秒触发一次,所以pc端用户操作过快会脱离

posted @ 2022-07-26 11:41  流云君  阅读(244)  评论(0编辑  收藏  举报