vue实现div拖拽

<template>
  <div>
    <el-form label-width="33%">
      <el-row>
        <el-col :span="2">
          <el-button type="primary" @click="addText">添加文本框</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addRadio">添加小圆点</el-button>
        </el-col>
      </el-row>
    </el-form>
    <p>&nbsp;</p>
    <div ref="pictureRef" style="position: relative;overflow: auto;border: 1px solid rgb(12, 14, 12);" @mouseup="up">
      <div
        v-for="item in pictureDivList"
        :id="item.value"
        :ref="item.value"
        :key="item.value"
        class="suspen"
        @mousedown="down(item.value)"
        @mouseup="up"
      ></div>
      <!-- 添加小圆点 -->
      <div
        v-for="item in pictureDivListRadio"
        :id="item.value"
        :ref="item.value"
        :key="item.value"
        class="suspenradio"
        @mousedown="down(item.value)"
        @mouseup="up"
      ></div>
      <img
        src="@/assets/bangye.jpg"
        draggable="false"
        style="width:100%;height:70%;object-fit: fill;object-fit: contain;object-fit: scale-down;float:left;"
      />
    </div>
    <!-- <el-button type="primary" @click="test">测试按钮</el-button>
    <div :style="classStyle"></div> -->
  </div>
</template>

<script>
  export default {
    data() {
      return {
        classStyle: 'width: 2vh;height: 2vh;background-color: green;border-radius: 50%;',
        keyShow: true,
        pictureDivList: [], //div文本框
        //为div拖拽数据
        isDown: false, //记录鼠标状态
        divId: '', //div标签的id
        move_div: '', //要操作的div对象
        m_move_x: '', //各种鼠标信息
        m_move_y: '', //各种鼠标信息
        m_down_x: '', //各种鼠标信息
        m_down_y: '', //各种鼠标信息
        dx: '', //各种鼠标信息
        dy: '', //各种鼠标信息
        md_x: '', //各种鼠标信息
        md_y: '', //各种鼠标信息
        ndx: '', //各种鼠标信息
        ndy: '', //各种鼠标信息
        pictureDivListRadio: [],
      }
    },
    methods: {
      addText() {
        let id = this.generateUUID()
        this.pictureDivList.push({ value: id })
        // this.keyShow = !this.keyShow
        // if (this.keyShow == true) {
        //   this.classStyle = 'width: 2vh;height: 2vh;background-color: green;border-radius: 50%;'
        // } else {
        //   this.classStyle = 'width: 2vh;height: 2vh;background-color: red;border-radius: 50%;'
        // }
      },
      addRadio() {
        //添加小圆点
        let id = this.generateUUID()
        this.pictureDivListRadio.push({ value: id })
      },
      generateUUID() {
        //生成uuid
        var d = new Date().getTime()
        if (window.performance && typeof window.performance.now === 'function') {
          d += performance.now() //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = (d + Math.random() * 16) % 16 | 0
          d = Math.floor(d / 16)
          return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
        })
        return uuid
      },
      down(divLabel) {
        //this.divId = divLabel
        this.move_div = document.getElementById(divLabel)
        this.isDown = true

        //获取鼠标按下时坐标
        this.m_down_x = event.pageX
        this.m_down_y = event.pageY
        //获取div坐标
        this.dx = this.move_div.offsetLeft
        this.dy = this.move_div.offsetTop
        //获取鼠标与div偏移量
        this.md_x = this.m_down_x - this.dx
        this.md_y = this.m_down_y - this.dy
        console.log('坐标')
        console.log(this.move_div.offsetLeft)
        console.log(this.move_div.offsetTop)
        var that = this
        document.onmousemove = function(ev) {
          if (that.isDown) {
            that.move_div = document.getElementById(divLabel)
            //实时更新div的坐标
            that.dx = that.move_div.offsetLeft
            that.dy = that.move_div.offsetTop

            //获取鼠标移动实时坐标
            that.m_move_x = ev.pageX
            that.m_move_y = ev.pageY

            //鼠标按下时移动才触发
            //if (this.isDown) {
            //获取新div坐标,鼠标实时坐标 - 鼠标与div的偏移量
            that.ndx = that.m_move_x - that.md_x
            that.ndy = that.m_move_y - that.md_y
            //把新div坐标值赋给div对象

            that.move_div.style.left = parseInt((that.ndx / that.$refs.pictureRef.getBoundingClientRect().width) * 100).toString() + '%'
            that.move_div.style.top = parseInt((that.ndy / that.$refs.pictureRef.getBoundingClientRect().height) * 100).toString() + '%'
            //将移动后的新坐标写入表格
            let locationXY = that.move_div.style.left + ',' + that.move_div.style.top
          }
        }
        //此处是为了防止在火狐浏览器下拖拽时会出现的两次阴影的效果,此处代码可以禁用
        document.onmouseup = function() {
          document.onmousemove = null
          document.onmouseup = null
        }
      },
      up(divLabel) {
        this.isDown = false
      },
      doubleEvent() {
        this.isDown = false
      },
    },
  }
</script>

<style lang="scss" scoped>
  .suspen {
    position: absolute;
    //position: relative;
    font-size: 20px;
    top: 15%; /*div的y轴*/
    left: 15%; /*div的x轴*/
    width: 8%;
    height: 4%;
    overflow: auto;
    zoom: 1;
    z-index: 999;
    background-color: yellow;
    border: 1px solid rgb(12, 14, 12);
    cursor: move;
  }
  .suspenradio {
    position: absolute;
    top: 15%; /*div的y轴*/
    left: 15%; /*div的x轴*/
    width: 15px;
    height: 15px;
    overflow: auto;
    zoom: 1;
    z-index: 999;
    background-color: red;
    // cursor: move;
    border-radius: 50%;
  }
</style>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现div拖拽互换位置可以使用Vue拖拽指令`v-drag`,具体实现步骤如下: 1. 在Vue组件中引入`v-drag`指令。 ```javascript import vDrag from 'v-drag'; ``` 2. 在Vue组件中注册`v-drag`指令。 ```javascript export default { directives: { vDrag }, // ... } ``` 3. 在模板中使用`v-drag`指令,并绑定相应的事件。 ```html <template> <div v-drag class="drag-item" @dragstart="handleDragStart" @dragend="handleDragEnd"> Drag me! </div> </template> ``` 4. 在事件处理方法中获取相应的拖拽数据,并实现拖拽效果。 ```javascript export default { // ... methods: { handleDragStart(event) { event.dataTransfer.setData('text', event.target.id); event.target.classList.add('dragging'); }, handleDragEnd(event) { event.target.classList.remove('dragging'); }, }, // ... } ``` 5. 实现拖拽交换位置的功能。通过监听`dragover`事件,获取当前被拖拽元素和目标元素的位置信息,并进行位置交换。 ```javascript export default { // ... methods: { // ... handleDragOver(event) { event.preventDefault(); const draggingEle = document.querySelector('.dragging'); const dropzone = event.target.closest('.dropzone'); if (!dropzone || dropzone === draggingEle) { return; } const draggingRect = draggingEle.getBoundingClientRect(); const dropzoneRect = dropzone.getBoundingClientRect(); if (event.clientY > (dropzoneRect.top + dropzoneRect.height / 2)) { dropzone.parentNode.insertBefore(draggingEle, dropzone.nextElementSibling); } else { dropzone.parentNode.insertBefore(draggingEle, dropzone); } }, }, // ... } ``` 完整代码示例: ```html <template> <div> <div class="dropzone" @dragover="handleDragOver"> <div v-drag class="drag-item" @dragstart="handleDragStart" @dragend="handleDragEnd"> Drag me! </div> <div v-drag class="drag-item" @dragstart="handleDragStart" @dragend="handleDragEnd"> Drag me too! </div> </div> </div> </template> <script> import vDrag from 'v-drag'; export default { directives: { vDrag }, methods: { handleDragStart(event) { event.dataTransfer.setData('text', event.target.id); event.target.classList.add('dragging'); }, handleDragEnd(event) { event.target.classList.remove('dragging'); }, handleDragOver(event) { event.preventDefault(); const draggingEle = document.querySelector('.dragging'); const dropzone = event.target.closest('.dropzone'); if (!dropzone || dropzone === draggingEle) { return; } const draggingRect = draggingEle.getBoundingClientRect(); const dropzoneRect = dropzone.getBoundingClientRect(); if (event.clientY > (dropzoneRect.top + dropzoneRect.height / 2)) { dropzone.parentNode.insertBefore(draggingEle, dropzone.nextElementSibling); } else { dropzone.parentNode.insertBefore(draggingEle, dropzone); } }, }, }; </script> <style scoped> .drag-item { width: 100px; height: 100px; background-color: #ddd; margin: 10px; text-align: center; line-height: 100px; cursor: move; } .dragging { opacity: 0.5; } .dropzone { display: flex; flex-wrap: wrap; border: 2px dashed #aaa; padding: 10px; } </style> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员阿明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值