HTML5-简单拖放操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5拖放操作示例</title>
<style>
#draggable {
width: 200px;
height: 200px;
background: skyblue;
color: white;
text-align: center;
line-height: 200px;
border: 2px dashed #333;
cursor: move;
}
#droppable {
width: 400px;
height: 400px;
background: orange;
position: absolute;
left: 400px;
top: 20px;
border: 2px solid #000;
}
</style>
</head>
<body>
<div id="draggable" draggable="true">拖动我</div>
<div id="droppable">放置区域</div>
<script>
const dragItem = document.getElementById('draggable');
const dropArea = document.getElementById('droppable');
dragItem.addEventListener('dragstart', function(event) {
event.dataTransfer.setData('text/plain', event.target.id);
});
dropArea.addEventListener('dragover', function(event) {
event.preventDefault(); // 阻止默认行为
event.dataTransfer.dropEffect = 'move'; // 设置拖放操作的视觉效果
});
dropArea.addEventListener('drop', function(event) {
event.preventDefault();
const id = event.dataTransfer.getData('text');
const draggedElement = document.getElementById(id);
dropArea.appendChild(draggedElement);
});
</script>
</body>
</html>
这段代码实现了一个简单的拖放操作。用户可以点击#draggable
元素并将其拖动到#droppable
元素内部,完成放置操作。代码中使用了dragstart
、dragover
和drop
事件,并通过event.dataTransfer
对象来管理拖放的数据。
评论已关闭