HTML5拖放(Drag and Drop)全面指南:让网页互动起来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and Drop Example</title>
<style>
#dropZone {
width: 300px;
height: 200px;
border: 2px dashed #aaa;
margin: 20px;
padding: 50px;
text-align: center;
font-size: 24px;
color: #aaa;
}
#draggables img {
width: 70px;
height: 70px;
margin: 10px;
cursor: move;
}
</style>
</head>
<body>
<div id="draggables">
<img src="image1.png" draggable="true" ondragstart="dragStart(event)">
<img src="image2.png" draggable="true" ondragstart="dragStart(event)">
<img src="image3.png" draggable="true" ondragstart="dragStart(event)">
</div>
<div id="dropZone" ondragover="dragOver(event)" ondrop="drop(event)">
将图片拖拽到这里
</div>
<script>
function dragStart(event) {
event.dataTransfer.setData("text/plain", event.target.id);
}
function dragOver(event) {
event.preventDefault(); // 阻止默认行为
}
function drop(event) {
event.preventDefault();
const id = event.dataTransfer.getData("text/plain");
const draggableElement = document.getElementById(id);
event.target.appendChild(draggableElement);
}
</script>
</body>
</html>
这个简化版的代码示例展示了如何使用HTML5的拖放API来创建一个可以拖放图片的区域。用户可以将图片元素从一个区域拖动到另一个区域中,实现页面元素的重新排序。
评论已关闭