如题,有啥好的实现思路,或者给个例子。
看了网上的例子实现了拖进去,但是拖出去不知道要如何实现让被拖动的元素拖出框就删除该元素
根据采纳答案,使用vue实现该功能
https://codesandbox.io/s/thir...
<template>
<div
class="hello"
@drop="dropHandle($event)"
@dragover="allowDropHandle($event)"
@dragstart="dragHandle($event)"
>
<span
draggable="true"
@dragstart="$event.dataTransfer.setData('text/plain', null)"
>我是谁我在哪</span
>
<div class="box">请拖曳到此松开</div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String,
},
setup() {
let dragged;
const dragHandle = (ev, type) => {
ev.dataTransfer.effectAllowed = "copy";
// ev.dataTransfer.dropEffect = "copy";
ev.dataTransfer.setData("text", null);
dragged = ev.target;
console.log(
"开始拖动",
dragged
// ev.target.parentNode,
// ev.target.parentNode.id
);
};
const dropHandle = (ev, date) => {
ev.preventDefault();
let data = ev.dataTransfer.getData("text");
let dupNode = dragged.cloneNode(true);
console.log(ev.target.className);
if (ev.target.className == "box") {
ev.target.appendChild(dupNode);
}
if (ev.target.className == "hello") {
dragged.parentNode.removeChild(dragged);
}
console.log("放", ev.target, ev.target.className, data);
};
const allowDropHandle = (ev) => {
// console.log('allowDrop', ev)
ev.dataTransfer.dropEffect = "copy";
ev.preventDefault();
};
return {
dragHandle,
dropHandle,
allowDropHandle,
};
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
span {
border: 1px solid #42b983;
}
.box {
width: 250px;
height: 200px;
border: 1px solid;
}
</style>
8 回答4.9k 阅读✓ 已解决
6 回答3.6k 阅读✓ 已解决
5 回答3k 阅读✓ 已解决
5 回答6.5k 阅读✓ 已解决
4 回答2.3k 阅读✓ 已解决
4 回答2.8k 阅读✓ 已解决
3 回答2.5k 阅读✓ 已解决
你既然用的原生的drag api,那直接在父组件里用removeChild()就好了啊
点击查看demo预览
主要代码: