VUE 創(chuàng)建頁面浮窗,拖拽事件與點擊事件共存

解決思路:

  • 記錄鼠標(biāo)按下時和鼠標(biāo)抬起時對應(yīng)的坐標(biāo)(pageX 和 pageY)
  • 通過開方將按下時位置與抬起時位置進(jìn)行比對,當(dāng)值等于0或者小于7時證明當(dāng)前為點擊事件,反之則是拖拽事件
  • 對應(yīng)的點擊事件寫在抬起鼠標(biāo)函數(shù)的判斷邏輯中即可

1.創(chuàng)建頁面浮窗并在初始化時固定位置

//創(chuàng)建 div,并添加按下鼠標(biāo)事件與抬起鼠標(biāo)事件
<div v-show="showCallCenter" class="call-center" @mousedown="move" @mouseup="moveEnd" ref="callCenter">
    <i class="el-icon-phone-outline"></i>
</div>
// 將div設(shè)置為圓形浮窗樣式
.call-center {
  color: #000;
  // 設(shè)置div大小
  width: 60px;
  height: 60px;
  // 設(shè)置div位置與變?yōu)閳A形
  top: 8%;
  right: 2%;
  border-radius: 50%;
  // 設(shè)為浮動并置于最頂層
  position: fixed;
  z-index: 99999;
  text-align: center;
  background: #eeeeee;
  border: 3px solid rgb(216, 194, 194);
  i {
    display: block;
    font-size: 32px;
    margin-top: 16px;
    color: #606266;
    transition: color 0.15s linear;
  }
}
image.png

2.初始化坐標(biāo)變量

data() {
    return {
      // 按下時的坐標(biāo)
      startX: '',
      startY: '',
      // 抬起時的坐標(biāo)
      endX: '',
      endY: '',
    }

3.添加鼠標(biāo)按下方法

methods: {
   // 拖動窗口,鼠標(biāo)按下
    move(event) {
      // 給對應(yīng)div添加拖拽屬性  
      let callCenter = this.$refs.callCenter
      callCenter.style.cursor = 'move'
      var distanceX = event.clientX - callCenter.offsetLeft
      var distanceY = event.clientY - callCenter.offsetTop
      // 獲取按下時對應(yīng)的坐標(biāo)
      this.startX = event.pageX
      this.startY = event.pageY
      document.onmousemove = function (ev) {
        var oevent = ev || event
        // 加入判斷,讓浮窗在限定的頁面內(nèi)可拖動
        if (ev.clientX < 40 || ev.clientX > document.body.clientWidth - 30) {
          return
        }
        if (ev.clientY < 40 || ev.clientY > document.body.clientHeight - 30) {
          return
        }
        callCenter.style.left = oevent.clientX - distanceX + 'px'
        callCenter.style.top = oevent.clientY - distanceY + 'px'
      }
      document.onmouseup = function () {
        document.onmousemove = null
        document.onmouseup = null
        callCenter.style.cursor = 'default'
      }
    }, 
}

4.添加鼠標(biāo)抬起方法

methods: {
    // 鼠標(biāo)抬起觸發(fā)
    moveEnd(event) {
      // 獲取鼠標(biāo)抬起時的坐標(biāo) 
      this.endX = event.pageX
      this.endY = event.pageY
      // 計算按下與抬起位置差值
      var d = Math.sqrt((this.startX - this.endX) * (this.startX - this.endX) + (this.startY - this.endY) * (this.startY - this.endY))
      if (d === 0 || d < 7) {
        console.log("執(zhí)行了點擊事件")
      }else {
          console.log("執(zhí)行了拖拽事件")
      }
    },
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容