HTMLJS实现元素拖拽排序
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽排序示例</title>
<style>
#drop_area {
width: 300px;
height: 50px;
border: 1px solid #000;
margin-bottom: 10px;
text-align: center;
line-height: 50px;
font-size: 24px;
color: #fff;
background-color: #00f;
cursor: pointer;
}
.drag_item {
width: 300px;
height: 50px;
margin: 10px 0;
text-align: center;
line-height: 50px;
font-size: 24px;
color: #fff;
background-color: #0f0;
cursor: move;
position: relative;
}
</style>
</head>
<body>
<div id="drop_area">放置区域</div>
<script>
// 拖拽函数
function dragStart(event) {
event.dataTransfer.setData("text/plain", event.target.id);
}
function allowDrop(event) {
event.preventDefault();
}
function drop(event) {
event.preventDefault();
const data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));
}
// 初始化拖拽
window.onload = function() {
const dragItems = document.getElementsByClassName("drag_item");
for (let i = 0; i < dragItems.length; i++) {
dragItems[i].draggable = true;
dragItems[i].addEventListener("dragstart", dragStart);
}
const dropArea = document.getElementById("drop_area");
dropArea.addEventListener("dragover", allowDrop);
dropArea.addEventListener("drop", drop);
};
</script>
</body>
</html>
这段代码实现了一个简单的拖拽排序功能。用户可以将 .drag_item
元素拖拽到 #drop_area
区域内,并且这些元素会根据拖拽的顺序放置在该区域内。
评论已关闭