利用元素的DnD事件(Drag and Drop),实现拖放源与拖放目标之间的数据传输:以下是一个示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript实现元素拖动</title>
<style>
*{
margin: 0;
}
#app{
width: 100vw;
height: 100vh;
background: #9acfea;
/*position: relative;*/
}
#content{
width: 200px;
height: 100px;
font-size: 20px;
line-height: 100px;
text-align: center;
/*position: fixed;*/
background: #ff6700;
border-radius: 10px;
cursor: pointer;
}
#drag_target{
width: 300px;
height: 300px;
position: absolute;
background: #1296db;
top: 30px;
left: 300px;
padding: 10px;
}
</style>
</head>
<body>
<div id="app">
<div id="content" data-type="0"></div>
<div id="drag_target" data-type="0"></div>
</div>
<script type="text/javascript">
let content = document.getElementById("content");
let drag_target = document.getElementById("drag_target");
content.innerHTML = new Date().toLocaleString();
content.draggable = true;
content.ondragstart = function (ev) {
console.log(ev);
let dt = ev.dataTransfer;
dt.effectAllowed = "move";
dt.setData("text",ev.target.id);
// dt.setDragImage(img,0,0);
};
drag_target.ondrop = function(ev){
console.log("drap...");
ev.preventDefault();
let data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
};
drag_target.ondragover = function(ev){
ev.target.style.borderRadius = "20px";
ev.target.style.border = "solid 1px #ff6700";
ev.preventDefault();
ev.dataTransfer.dropEffect = "move"
};
</script>
</body>
</html>
显示效果