[vue3]实现div拖拽定位

自定义方法实现拖拽

首先,你需要定义一个自定义指令,比如 v-drag,用来实现拖拽的逻辑。你可以在 <script setup> 中,使用一个以 v 开头的驼峰式命名的变量,作为指令的名称。指令的值是一个对象或函数,用来定义指令的钩子函数和参数。

在指令的钩子函数中,你可以使用 el 参数来操作绑定元素的 DOM,比如添加事件监听器,修改样式等。你也可以使用 binding 参数来获取指令绑定的值,参数,修饰符等。

下面是一个简单的例子,实现了一个可以拖拽的 div:

<template>
  <div v-drag class="box">拖拽我</div>
</template>

<script setup>
  // 定义一个自定义指令,用来实现拖拽的逻辑
  const vDrag = {
    // 在元素被插入到 DOM 前调用
    beforeMount(el) {
      // 定义一些变量,用来存储拖拽的状态
      let isDown = false // 是否按下鼠标
      let offsetX = 0 // 鼠标相对于元素的水平偏移量
      let offsetY = 0 // 鼠标相对于元素的垂直偏移量

      // 定义一个函数,用来处理鼠标按下的事件
      function handleMouseDown(e) {
        // 设置按下的标志为 true
        isDown = true
        // 计算鼠标相对于元素的偏移量
        offsetX = e.clientX - el.offsetLeft
        offsetY = e.clientY - el.offsetTop
      }

      // 定义一个函数,用来处理鼠标移动的事件
      function handleMouseMove(e) {
        // 如果按下的标志为 true,才执行拖拽的逻辑
        if (isDown) {
          // 计算元素的新位置
          let left = e.clientX - offsetX
          let top = e.clientY - offsetY
          // 设置元素的样式,使其移动到新位置
          el.style.left = left + 'px'
          el.style.top = top + 'px'
        }
      }

      // 定义一个函数,用来处理鼠标松开的事件
      function handleMouseUp() {
        // 设置按下的标志为 false
        isDown = false
      }

      // 给元素添加鼠标按下的事件监听器
      el.addEventListener('mousedown', handleMouseDown)
      // 给 document 添加鼠标移动的事件监听器,这样可以使元素跟随鼠标移动,即使鼠标移出了元素的范围
      document.addEventListener('mousemove', handleMouseMove)
      // 给 document 添加鼠标松开的事件监听器,这样可以使元素停止移动,即使鼠标松开在元素外面
      document.addEventListener('mouseup', handleMouseUp)
    },
    // 在绑定元素的父组件卸载后调用
    unmounted(el) {
      // 移除之前添加的事件监听器,避免内存泄漏
      el.removeEventListener('mousedown', handleMouseDown)
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
    }
  }
</script>

<style>
  /* 设置一些样式,使 div 可以拖拽 */
  .box {
    width: 100px;
    height: 100px;
    background: skyblue;
    position: absolute;
    left: 0;
    top: 0;
    cursor: move;
    user-select: none;
  }
</style>

实现拖拽的思路大致如此,但是自定义方法的弊端,无法复用,下面优化下思路,封装一个可复用,灵活度更高的可拖拽组件

封装可拖拽的组件

DraggableItem组件通过插槽存放不同类型的内容,包括文本、图片和图表。这样就可以在多个div中分别放置不同类型的内容,并且仍然可以实现拖拽效果。

根据传入的directionLR和directionTB决定组件的初始定位方向,根据styleCss中的leftRight和topBottom设置定位参数

<template>
  <div
      class="draggable"
      :style="{ [directionLR]: `${styleCss.leftRight}px`, [directionTB]: `${styleCss.topBottom}px` }"
      @mousedown="startDrag($event)"
      @mousemove="drag($event)"
      @mouseup="endDrag()"
  >
    <slot></slot>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
const props = defineProps({
  initialLeft: {
    type: Number,
    default: 0
  },
  initialTop: {
    type: Number,
    default: 0
  },
  directionLR: {
    type: String,
    required: true
  },
  directionTB: {
    type: String,
    required: true
  },
})
const styleCss = ref({
  leftRight: props.initialLeft,
  topBottom: props.initialTop,
  isDragging: false, // 拖拽标识
})
const offsetX = ref(0)
const offsetY = ref(0)
const startDrag = (event) => {
  styleCss.value.isDragging = true;
  if(props.directionLR==="left"){
    offsetX.value = event.clientX - styleCss.value.leftRight
  }else if(props.directionLR==="right"){
    offsetX.value = event.clientX + styleCss.value.leftRight
  }

  if(props.directionTB==="top"){
    offsetY.value = event.clientY - styleCss.value.topBottom
  }else if(props.directionTB==="bottom"){
    offsetY.value = event.clientY + styleCss.value.topBottom
  }
}
const drag = (event) => {
  if ( styleCss.value.isDragging) {
    if(props.directionLR==="left"){
      styleCss.value.leftRight = event.clientX - offsetX.value
    }else if(props.directionLR==="right"){
      if(offsetX.value>event.clientX){
        styleCss.value.leftRight = offsetX.value - event.clientX
      }else {
        styleCss.value.leftRight =  event.clientX - offsetX.value
      }
    }

    if(props.directionTB==="top"){
      styleCss.value.topBottom = event.clientY - offsetY.value
    }else if(props.directionTB==="bottom"){
      if(offsetY.value>event.clientY){
        styleCss.value.topBottom = offsetY.value - event.clientY
      }else {
        styleCss.value.topBottom =  event.clientY - offsetY.value
      }
    }
  }


}
const  endDrag = () => {
  styleCss.value.isDragging = false;
}
</script>

<style scoped>
.draggable {
  z-index: 100;
  position: absolute;
  cursor: move;
  user-select: none;
}
</style>
 调用

   在父组件中引用DraggableItem组件,并向其传递定位 参数设置div初始的位置。例如:

<template>
 <draggable :initialLeft="20" :initialTop="56" :directionLR="'left'" :directionTB="'top'">
  <img class="compass-img" :src="getAssetsFile(`thematicMapping/${ployForm.compass}.png`)">
 </draggable>
    <!--图例-->
  <draggable :initialLeft="20" :initialTop="50" :directionLR="'left'" :directionTB="'bottom'">
    <div class="map-legend">
      <div class="legendOne" id="legendOne"></div>
    </div>
  </draggable>
</template>

<script setup>
import DraggableItem from './DraggableItem.vue';
</script>
<style scoped lang = "less">
  .map-legend{
  width: 200px;
  height: auto;
  display: flex;
  flex-direction: column;
  pointer-events: none;
}
  .compass-img{
  width: 40px;
  height: 40px;
  background: white;
  pointer-events: none;
}
</style>

在父组件中调用,并传入定位参数,如果是图片,需要设置pointer-events: none;,避免图片被选中,影响拖拽效果。

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现 div 横向拖动并互换位置,可以使用 Vue.js 和一些 JavaScript 库来实现。 首先,你需要在 Vue.js 中创建一个拖动事件。你可以使用 `v-on:mousemove` 来监听鼠标移动事件,并使用 `v-on:mousedown` 来监听鼠标按下事件。在鼠标按下事件中,你需要记录鼠标的当前位置。 接下来,在鼠标移动事件中,你需要计算鼠标的偏移量,并将偏移量添加到 div 的 left 样式中。这将使 div 沿着 x 轴移动。 当鼠标释放时,你需要计算 div 的位置,并使用 JavaScript 库来实现 div 位置的互换。你可以使用 Sortable.js 或者 Draggable.js 这样的库来实现拖拽和位置交换。 最后,你需要将这些逻辑封装在一个 Vue.js 组件中,以便在应用程序中使用。以下是一个简单的示例: ```html <template> <div class="container"> <div v-for="(item, index) in items" :key="index" :class="{ active: activeIndex === index }" v-bind:style="{ left: item.left + 'px' }" v-on:mousedown="startDrag(index, $event)"> {{ item.text }} </div> </div> </template> <script> import Sortable from 'sortablejs'; export default { data() { return { items: [ { text: 'Item 1', left: 0 }, { text: 'Item 2', left: 100 }, { text: 'Item 3', left: 200 }, { text: 'Item 4', left: 300 }, ], activeIndex: null, startX: 0, }; }, mounted() { const container = this.$el.querySelector('.container'); Sortable.create(container, { animation: 150, swapThreshold: 0.5, onSwap: (evt) => { const { oldIndex, newIndex } = evt; const item = this.items.splice(oldIndex, 1)[0]; this.items.splice(newIndex, 0, item); }, }); }, methods: { startDrag(index, event) { this.activeIndex = index; this.startX = event.clientX; window.addEventListener('mousemove', this.drag); window.addEventListener('mouseup', this.stopDrag); }, drag(event) { const deltaX = event.clientX - this.startX; this.items[this.activeIndex].left += deltaX; this.startX = event.clientX; }, stopDrag() { window.removeEventListener('mousemove', this.drag); window.removeEventListener('mouseup', this.stopDrag); this.activeIndex = null; }, }, }; </script> <style> .container { display: flex; position: relative; width: 100%; height: 100px; background-color: #f5f5f5; } .container > div { position: absolute; top: 0; height: 100%; width: 100px; background-color: #fff; border: 1px solid #ccc; display: flex; justify-content: center; align-items: center; cursor: move; } .container > div.active { z-index: 1; } </style> ``` 在这个示例中,我们创建了一个包含多个 div 的容器,并使用 Vue.js 的数据绑定将每个 div 的位置绑定到数据模型中。当用户按下鼠标并开始拖动 div 时,我们记录 div 的当前位置,并在每次移动时计算偏移量。当用户释放鼠标时,我们使用 Sortable.js 库来实现 div 的位置交换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值