不想要 vuedraggable 原生半透明拖拽效果?fallback 来帮忙

385 阅读1分钟

使用 vuedraggable,鼠标拖拽的时候随鼠标移动的元素是半透明的,这是浏览器原生的效果。比如像下面这样:

<template>
  <draggable v-model="list" animation="200">
    <transition-group tag="div" class="list-group">
      <div v-for="item in list" :key="item" class="item">{{ item }}</div>
    </transition-group>
  </draggable>
</template>

image.png

其实 Sortable 支持自定义拖拽时的效果,它提供了 fallback 相关配置项来自定义拖拽时的一些行为。来看看官方文档都有哪些相关配置:

{
    ghostClass: "sortable-ghost",  // Class name for the drop placeholder
    chosenClass: "sortable-chosen",  // Class name for the chosen item
    dragClass: "sortable-drag",  // Class name for the dragging item
    forceFallback: false,  // ignore the HTML5 DnD behaviour and force the fallback to kick in
    fallbackClass: "sortable-fallback",  // Class name for the cloned DOM Element when using forceFallback
    fallbackOnBody: false,  // Appends the cloned DOM Element into the Document's Body
}

主要用到4个,ghost-class 是拖拽元素的占位类名,需要把样式设置成透明看不到,forceFallback 是开启 fallback 自定义拖拽行为,fallbackClass 是拖拽时随鼠标移动元素的类名,通过这个类可以自定义各种想要的拖拽目标样式,fallbackOnBody 建议设为 true,避免一些奇怪的样式问题。

<template>
  <draggable
    v-model="list"
    animation="200"
    ghost-class="ghost"
    :forceFallback="true"
    :fallbackOnBody="true"
    fallbackClass="fallback"
  >
    <transition-group tag="div" class="list-group">
      <div v-for="item in list" :key="item" class="item">{{ item }}</div>
    </transition-group>
  </draggable>
</template>

<style>
.ghost {
  opacity: 0;
}
.fallback {
  opacity: 1 !important;
  background: #fff;
  border: 1px solid red;
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.1);
}
</style>

这样就得到了想要的效果:

image.png

fallbackOnBody 设为 true,拖拽时的移动元素就会添加到 body。

image.png