html5-drag和drop拖拽
HTML5提供了拖拽事件,可以用来创建拖拽和放置功能。以下是一个简单的拖拽和放置的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and Drop Example</title>
<style>
#draggable {
width: 150px;
height: 150px;
background: red;
color: white;
text-align: center;
line-height: 150px;
border: 2px dashed #333;
cursor: move;
position: absolute;
top: 50px;
left: 50px;
}
#droppable {
width: 300px;
height: 300px;
background: green;
position: absolute;
top: 50px;
left: 250px;
border: 2px dashed #333;
}
</style>
</head>
<body>
<div id="draggable" draggable="true">Drag me!</div>
<div id="droppable">Drop here!</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();
});
dropArea.addEventListener('drop', function(event) {
event.preventDefault();
const data = event.dataTransfer.getData('text/plain');
event.target.appendChild(document.getElementById(data));
});
</script>
</body>
</html>
在这个例子中,我们创建了两个div
元素,一个可以拖动(draggable
),另一个可以放置(droppable
)。通过JavaScript,我们为可拖动的元素添加了dragstart
事件监听器,该监听器在拖动开始时设置要传输的数据(这里是元素的ID)。同时,我们为可放置的元素添加了dragover
和drop
事件监听器,分别阻止默认行为并在放置时将拖动的元素添加为子元素。
评论已关闭