以下是一个基于Vue2的实现dialog弹框可拖拽的代码示例:

<template>
  <div class="dialog" :style="{ top: top + 'px', left: left + 'px' }" @mousedown="startDrag">
    <div class="titlebar" @mouseup="stopDrag">{{ title }}</div>
    <div class="content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DraggableDialog',
  props: {
    title: String,
    x: Number,
    y: Number
  },
  data() {
    return {
      dragging: false,
      relX: 0,
      relY: 0,
      top: this.y || 0,
      left: this.x || 0,
      maxX: window.innerWidth - 200, // 限制最大X坐标
      maxY: window.innerHeight - 100 // 限制最大Y坐标
    }
  },
  methods: {
    startDrag(event) {
      this.dragging = true
      this.relX = event.clientX - this.left
      this.relY = event.clientY - this.top
      window.addEventListener('mousemove', this.handleMouseMove)
    },
    stopDrag() {
      this.dragging = false
      window.removeEventListener('mousemove', this.handleMouseMove)
    },
    handleMouseMove(event) {
      if (this.dragging) {
        let newLeft = event.clientX - this.relX
        let newTop = event.clientY - this.relY
        // 限制最小X坐标
        if (newLeft < 0) {
          newLeft = 0
        }
        // 限制最小Y坐标
        if (newTop < 0) {
          newTop = 0
        }
        // 限制最大X坐标
        if (newLeft > this.maxX) {
          newLeft = this.maxX
        }
        // 限制最大Y坐标
        if (newTop > this.maxY) {
          newTop = this.maxY
        }
        this.left = newLeft
        this.top = newTop
      }
    }
  }
}
</script>

<style scoped>
.dialog {
  position: absolute;
  width: 200px;
  height: 100px;
  background-color: #fff;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
  cursor: move;
}

.titlebar {
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  font-weight: bold;
  padding: 0 10px;
  background-color: #e3e3e3;
  cursor: move;
}

.content {
  padding: 10px;
}
</style>

在上面的代码中,我们通过@mousedown监听鼠标按下事件,然后通过@mouseup监听鼠标松开事件,以控制dialog弹框的拖拽行为。在鼠标按下事件的处理函数中,我们记录下当前鼠标相对于dialog弹框左上角的偏移量,然后通过window.addEventListener('mousemove', this.handleMouseMove)注册一个全局的鼠标移动事件监听函数handleMouseMove,来实时更新dialog弹框的位置。在鼠标松开事件的处理函数中,我们则取消掉鼠标移动事件的监听。

handleMouseMove函数中,我们通过计算当前鼠标所在位置相对于dialog弹框左上角的坐标,来更新dialog弹框的位置。同时,我们加入了一些限制条件,以限制dialog弹框的移动范围,防止其移动到屏幕外面去

vue2怎样实现dialog弹框可拖拽代码怎么写加上上下限制 不能出界面

原文地址: http://www.cveoy.top/t/topic/g1nC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录