div拖拽互换位置

该博客介绍了如何在前端使用Vue实现div元素的拖拽功能,允许用户通过拖放操作改变div元素的顺序。主要涉及的事件监听包括dragstart、dragover、dragenter和dragend,以及相应的处理函数,如handleDragStart、handleDragEnd和handleDragEnter。通过修改targetKeys数组来更新div的排列顺序,并触发'chageTarget'事件。

<transition-group tag="div">

            <div

              v-for="(item, index) in targetKeys"

              :key="index"

              ref="list"

              class="option-item"

              draggable="true"

              @dragstart="handleDragStart(item)"

              @dragover.prevent="handleDragOver($event)"

              @dragenter="handleDragEnter($event, item)"

              @dragend="handleDragEnd()"

            >

              <close-outlined @click="closeTargetKey(item, onItemSelect)" />

              <div class="item-info">

                <div class="item-title">{{ getStation(item)?.name }}</div>

                <div class="item-coord">{{ getStation(item)?.coord }}</div>

              </div>

              <unordered-list-outlined :style="{ fontSize: '20px' }" />

            </div>

          </transition-group>

 /**

   * 拖拽方法块

   */

  const dragging = ref();

  function handleDragStart(item: any) {

    dragging.value = item;

  }

  function handleDragEnd() {

    dragging.value = null;

  }

  //首先把div变成可以放置的元素,即重写dragenter/dragover

  function handleDragOver(e: any) {

    e.dataTransfer.dropEffect = 'move'; // e.dataTransfer.dropEffect="move";//在dragenter中针对放置目标来设置!

  }

  function handleDragEnter(e: any, item: any) {

    e.dataTransfer.effectAllowed = 'move'; //为需要移动的元素设置dragstart事件

    if (dragging.value === item) {

      return null;

    }

    const newItems = [...targetKeys.value];

    const src = newItems.indexOf(dragging.value);

    const dst = newItems.indexOf(item);

    newItems.splice(dst, 0, ...newItems.splice(src, 1));

    targetKeys.value = newItems;

    emits('chageTarget');

  }

.option-item {

      background: #ebeff3;

      border-radius: 2px;

      height: 32px;

      width: 100%;

      display: flex;

      align-items: center;

      justify-content: space-between;

      .item-info {

        display: flex;

        align-items: center;

        justify-content: space-between;

        flex: auto;

        padding: 0 10px;

        .item-title {

          font-family: PingFangSC-Regular;

          font-size: 14px;

          color: #272a33;

        }

      }

    }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值