1 回答
TA贡献1828条经验 获得超3个赞
我已经让它动态化了,你现在可以拖动 div、图像,我会注意拖动元素的顺序。现在您可以修改它以存储在您的服务器而不是客户端中。快乐编码:)
<!DOCTYPE HTML>
<html>
<head>
<title>Retrieve drag position</title>
<meta charset="utf-8">
<style>
* {
box-sizing: border-box;
}
.drop_box {
width: 100px;
height: 120px;
margin: 10px;
padding: 5px;
border: 1px solid black;
}
img, .dragged_box {
width: 90px;
height: 30px;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
</style>
</head>
<body onload="retrieve()">
<div class="dragged_box red" draggable="true" ondragstart="drag(event)" id="drag_div1"></div>
<div class="dragged_box blue" draggable="true" ondragstart="drag(event)" id="drag_div2"></div>
<div class="dragged_box green" draggable="true" ondragstart="drag(event)" id="drag_div3"></div>
<img src="https://img.icons8.com/color/48/000000/bungalow.png" draggable="true" ondragstart="drag(event)" id="drag_img1">
<img src="https://img.icons8.com/ios-filled/50/000000/bungalow.png" draggable="true" ondragstart="drag(event)" id="drag_img2">
<img src="https://img.icons8.com/ios/50/000000/bungalow.png" draggable="true" ondragstart="drag(event)" id="drag_img3">
<div class="drop_box" id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div class="drop_box" id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div class="drop_box" id="div3" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div class="drop_box" id="div4" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<script>
var draggedImages = {
draggedIds: [],
droppedIds: []
}
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var id = ev.dataTransfer.getData("text");
if(draggedImages.draggedIds.indexOf(id) === -1) {
draggedImages.draggedIds.push(id);
draggedImages.droppedIds.push(ev.target.id);
}else {
var ind = draggedImages.draggedIds.indexOf(id);
// to keep the order of images
draggedImages.draggedIds.splice(ind, 1);
draggedImages.droppedIds.splice(ind, 1);
draggedImages.draggedIds.push(id);
draggedImages.droppedIds.push(ev.target.id);
}
localStorage["draggedImages"] = JSON.stringify(draggedImages);
ev.target.appendChild(document.getElementById(id));
}
function retrieve() {
if(localStorage["draggedImages"]) {
draggedImages = JSON.parse(localStorage["draggedImages"]);
draggedImages.draggedIds.forEach(function(draggedId, ind) {
document.getElementById(draggedImages.droppedIds[ind]).appendChild(document.getElementById(draggedId));
});
}
}
</script>
</body>
</html>
添加回答
举报