CSS3拖拽排序

<template>
  <div class="root">
    <transition-group tag="div" class="container">
      <div
          class="item"
          :class="'item' + i"
          v-for="(item, i) in items"
          :key="item.key"
          :style="{ 'background-color': item.color, border: '1px solid' }"
          draggable="true"
          @dragstart="handleDragStart($event, item)"
          @dragover.prevent="handleDragOver($event, item)"
          @dragenter="handleDragEnter($event, item)"
          @dragend="handleDragEnd($event, item)"
      >
        <div>{{ item }}</div>
      </div>
    </transition-group>
  </div>
</template>

<script>
export default {
  name: "test",
  data() {
    return {
      items: [
        { key: 1, color: "#3883a0" },
        { key: 2, color: "#4883a0" },
        { key: 3, color: "#5883a0" },
        { key: 4, color: "#6883a0" },
        { key: 5, color: "#7883a0" },
        { key: 6, color: "#8883a0" },
        { key: 7, color: "#9883a0" },
      ],
      ending: null,
      dragging: null,
    };
  },
  methods: {
    handleDragStart(e, item) {
      this.dragging = item;
    },
    handleDragEnd() {
      if (this.ending.key === this.dragging.key) {
        return;
      }
      let newItems = [...this.items];
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(this.ending);
      newItems.splice(src, 1, ...newItems.splice(dst, 1, newItems[src]));
      console.log(newItems);

      this.items = newItems;
      this.$nextTick(() => {
        this.dragging = null;
        this.ending = null;
      });
    },
    handleDragOver(e) {
      // 首先把div变成可以放置的元素,即重写dragenter/dragover
      // 在dragenter中针对放置目标来设置
      e.dataTransfer.dropEffect = "move";
    },
    handleDragEnter(e, item) {
      // 为需要移动的元素设置dragstart事件
      e.dataTransfer.effectAllowed = "move";
      this.ending = item;
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-wrap: wrap;
}
.item {
  width: 23%;
  height: 200px;
  margin: 10px;
  color: #fff;
  transition: all linear 0.3s;
}
</style>

记一个多行多列的交换拖拽排序。

效果图如下:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值