默认拖拽数据
默认拖拽元素会自带拖拽数据,非默认拖拽元素不会自带拖拽数据。
示例
1.默认拖拽元素
1.1.图片
1.2.文本
1.3.链接
2.非默认拖拽元素
代码DEMO
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.imgIcon {
width: 100px;
height: auto;
}
.position1 {
position: absolute;
top: 0;
left: 0;
}
p {
position: relative;
padding: 20px;
border: 1px solid grey;
}
.div-box {
border: 1px solid skyblue;
height: 500px;
}
.div-box:-moz-drag-over {
border: 1px solid black;
}
</style>
</head>
<body>
<img src="../img/1.webp" alt="" class="imgIcon" ondragstart="dragstart(event)">
<p ondragstart="dragstart(event)">这是一个不能拖拽的元素,可拖拽其内部的文本</p>
<a href="https://developer.mozilla.org/zh-CN/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations" ondragstart="dragstart(event)">链接</a>
<p draggable="true" ondragstart="dragstart(event)">这是一个非默认拖拽元素</p>
<div class="div-box" ondragenter="dragenter(event)" ondragover="dragover(event)" ondrop="drop(event)">
</div>
<script>
const dragstart = (event) => {
// console.log(event.dataTransfer.types)
// 在这个事件中调用 getData 没有效果
// var data = event.dataTransfer.getData("")
// console.log(data)
}
const dragenter = (event) => {
}
const dragover = (event) => {
event.preventDefault()
}
const drop = (event) => {
var data = event.dataTransfer.getData("text");
console.log('drop事件', data)
}
</script>
</body>
</html>
自定义拖拽数据
自定义的数据是拖拽元素的id,并且在拖拽之后将元素放入到目标元素中。
效果图
代码DEMO
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.imgIcon {
width: 100px;
height: auto;
}
.position1 {
position: absolute;
top: 0;
left: 0;
}
p {
position: relative;
padding: 20px;
border: 1px solid grey;
}
.div-box {
border: 1px solid skyblue;
height: 500px;
}
.div-box:-moz-drag-over {
border: 1px solid black;
}
</style>
</head>
<body>
<p draggable="true" ondragstart="dragstart(event)" id="paragraph">这是一个非默认拖拽元素</p>
<div class="div-box" ondragenter="dragenter(event)" ondragover="dragover(event)" ondrop="drop(event)">
</div>
<script>
const type = 'test/lala'
const dragstart = (event) => {
event.dataTransfer.setData(type, event.target.id)
console.log(event.dataTransfer.types)
}
const dragenter = (event) => {
}
const dragover = (event) => {
event.preventDefault()
}
const drop = (event) => {
var data = event.dataTransfer.getData(type);
console.log('drop事件', data)
const el = document.getElementById(data)
event.target.appendChild(el)
}
</script>
</body>
</html>