赞
踩
写了一个列表的拖拽排序,但遇到一个问题,就是拖拽放下后,html元素总会有一个回落的默认效果,这个会影响排序效果。
其实,最后解决的办法,也很简单,就是在dragover事件处理中,去除默认,也就是e.preventDefault();
const onDragOver = (e: any, index: number) => {
e.preventDefault();
// ....
}
<template> <div> <div class="card-list"> <div class="card-item" :class="{'drag-over': dragOverIndex === index, 'active': dragData.index == index}" v-for="(item, index) in dataList" :key="item.cocosData.id" :id="item.cocosData.id" draggable="true" @dragstart.stop="onDragStart($event, index)" @dragover.stop="onDragOver($event, index)" @dragend.stop="onDragend" > <span>{{ item }}</span> </div> </div> </div> </template> <script lang="ts"> import { ref } from "vue"; export default defineComponent({ name: "DragSort", setup(props) { const dataList = ref<string[]>([ "字母A", "字母B", "字母D", "p", ]); const dragData = ref<any>({}); const onDragStart = (e: any, index: number) => { dragData.value = { index, } } const dragOverIndex = ref(-1); const onDragOver = (e: any, index: number) => { e.preventDefault(); if (dragData.value.index != index) { dragOverIndex.value = index; } else { dragOverIndex.value = -1; } } const onDragend = (e: any) => { e.preventDefault(); const dragIndex = dragData.value.index; // console.log('onDragend', dragIndex, dragOverIndex.value); if (dragIndex != dragOverIndex.value && dragOverIndex.value != -1) { const dragItem = dataList[dragIndex]; // console.log('dragItem', dragItem); if (dragOverIndex.value > dragIndex) { dataList.splice(dragOverIndex.value + 1, 0, dragItem); dataList.splice(dragIndex, 1); } else { dataList.splice(dragIndex, 1); dataList.splice(dragOverIndex.value, 0, dragItem); } } dragOverIndex.value = -1; dragData.value = {}; } return { dataList, onDragStart, onDragOver, dragOverIndex, onDragend, dragData, }; }, }); </script> <style lang="less" scoped> .card-list { margin-top: 10px; .card-item { display: flex; justify-content: space-between; align-items: center; border: 1px solid transparent; position: relative; &.active { background-color: #f2f2f2; } &.drag-over { background-color: #ddd; border: 1px solid #aaa; } span { cursor: pointer; } } } </style>
欢迎各位来用下我用了近2年,搞的一款网页编辑器,一定会让你感到惊讶的,哈哈!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。