自学内容网 自学内容网

vue3弹框拖拽功能

 

<div  @mousedown="startDrag">
    
  </div>
import { useDrag } from '@/views/WholeNetworkNewView/components/3D/BaseStationPanel/useDrag.js'

const { startDrag } = useDrag()
import { ref, onMounted, onBeforeUnmount } from 'vue'

export function useDrag() {
  const isDragging = ref(false)
  const offset = ref({ x: 0, y: 0 })
  const modal = ref(null)
  let zIndexCounter = 1000 // 初始 z-index 值

  const startDrag = (e) => {
    const targetId = e.currentTarget.id
    //const targetId = e.target.id
    if (targetId) {
      isDragging.value = true
      offset.value.x = e.clientX - e.currentTarget.offsetLeft
      offset.value.y = e.clientY - e.currentTarget.offsetTop
      modal.value = e.currentTarget // 动态设置 modal 为当前拖拽的元素
      zIndexCounter += 1
      modal.value.style.zIndex = zIndexCounter // 设置 z-index 使其置顶
    }
  }

  const onMouseMove = (e) => {
    // 如果正在拖动并且模态框存在
    if (isDragging.value && modal.value) {
      // 更新模态框的left样式,使其跟随鼠标移动
      modal.value.style.left = `${e.clientX - offset.value.x}px`
      // 更新模态框的top样式,使其跟随鼠标移动
      modal.value.style.top = `${e.clientY - offset.value.y}px`
    }
  }

  const stopDrag = () => {
    isDragging.value = false
  }

  onMounted(() => {
    document.addEventListener('mousemove', onMouseMove)
    document.addEventListener('mouseup', stopDrag)
  })

  onBeforeUnmount(() => {
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', stopDrag)
  })

  return {
    startDrag
  }
}

 

 

 

 


原文地址:https://blog.csdn.net/qq_38260470/article/details/145174923

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!