背景:
前端项目中使用了draggable属性来实现拖拽,相比于使用插件,draggable的灵活度很高。但是发现拖动元素在拖动过程中的透明度会统一变低,当拖动元素较大时会出现虚化的情况(如下图),这样的拖动效果很不好,这里记录一下解决过程。
最终效果:
前情提要:
draggable的使用参考文档
实现代码:
<template>
<div style="margin-left: 50px">
<div class="dragWrap">
<span class="info">原本位置</span>
<div
class="dragBox"
draggable
@drag="handleDrag"
@dragstart="handleDragStart"
@dragend="handleDragEnd"
></div>
</div>
<div class="targetBox" @dragover="handleDragOver">目标位置</div>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
@Component({ components: {} })
export default class myClass extends Vue {
cloneObj: any = null; // 拖动元素副本
handleDrag(e: any) {
if (this.cloneObj) {
const width = this.cloneObj.clientWidth;
const height = this.cloneObj.clientHeight;
this.cloneObj.style.transform =
'translate3d( ' + (e.clientX - width / 2) + 'px ,' + (e.clientY - height / 2) + 'px,0)';
e.target.style.display = 'none';
}
}
handleDragStart(e: any) {
let img = new Image();
img.src = '';
e.dataTransfer.setDragImage(img, 0, 0); // 将拖拽显示图片设为空
this.cloneObj = e.target.cloneNode(true); // 存储元素副本
this.cloneObj.style =
'position:fixed;left:0;top:0;z-index:999;pointer-events:none;transform:translate3d(' +
(e.clientX - 175) +
'px,' +
(e.clientY - 75) +
'px,0);'; // 设置初始位置
document.body.appendChild(this.cloneObj);
console.log(e.target, this.cloneObj, '///当前正在拖动的元素');
}
handleDragEnd(e: any) {
document.body.removeChild(this.cloneObj); // 复原
this.cloneObj = null;
e.target.style.display = 'block';
console.log('ending....');
}
handleDragOver(e: any) {
e.preventDefault();
}
}
</script>
<style lang="scss" scoped>
.dragWrap {
width: 350px;
height: 150px;
position: relative;
border: 1px solid red;
}
.dragBox {
width: 350px;
height: 150px;
background-color: black;
}
.targetBox {
width: 500px;
height: 500px;
margin-top: 30px;
border: 1px solid red;
}
.info {
position: absolute;
z-index: -1;
}
</style>