vue中鼠标拖动div,(多个div)跟随卡顿问题

vue写法非常的卡顿

 

注释:因为有多个div需要拖动所以我用下标把不同坐标数据分开

data数据

页面会渲染五个div我就傻瓜式定义了五个坐标数据,欢迎大佬提供更好的办法

vue中鼠标拖动div,(多个div)跟随卡顿问题_第1张图片

i就是下标主要用来区分这五个div

isDragable是等鼠标抬起时候不要在让div跟随鼠标移动了
 down(e, i) {
      let dragObj = this.$refs['box' + i][0]
      this['isDragable' + i] = true
      this['currentX' + i] = e.clientX
      this['currentY' + i] = e.clientY
      this['objX' + i] = dragObj.offsetLeft
      this['objY' + i] = dragObj.offsetTop
    },

    move(e, i) {
      let dragObj = this.$refs['box' + i][0]
      if (this['isDragable' + i]) {
        let moveX = e.clientX - this['currentX' + i]
        let moveY = e.clientY - this['currentY' + i]
        dragObj.style.left = this['objX' + i] + moveX + 'px'
        dragObj.style.top = this['objY' + i] + moveY + 'px'
        dragObj.style.zIndex = 100
      }
    },
    
    up(e, i) {
      let dragObj = this.$refs['box' + i][0]
      this['isDragable' + i] = false
      dragObj.style.zIndex = 1
    },

解决办法:使用原生document监听鼠标的坐标,拖动起来非常的丝滑

    

vue中鼠标拖动div,(多个div)跟随卡顿问题_第2张图片

	 down(e, i) {
      let dragObj = this.$refs['box' + i][0]
      this.isMouseDown = true
      this['currentX' + i] = e.clientX
      this['currentY' + i] = e.clientY
      this['objX' + i] = dragObj.offsetLeft
      this['objY' + i] = dragObj.offsetTop
      console.log(document)
      document.onmousemove = e => {
        if (!this.isMouseDown) return
        let moveX = e.clientX - this['currentX' + i]
        let moveY = e.clientY - this['currentY' + i]
        dragObj.style.left = this['objX' + i] + moveX + 'px'
        dragObj.style.top = this['objY' + i] + moveY + 'px'
        dragObj.style.zIndex = 100 //让拖动的div权重最大
      }
      document.onmouseup = e => {
        if (!this.isMouseDown) return
        this.isMouseDown = false //鼠标抬起时候不要在跟随鼠标移动
        dragObj.style.zIndex = 1
      }
    },

你可能感兴趣的:(html,vue.js,javascript)