js实现拖拽功能
在JavaScript中实现拖拽功能通常需要监听鼠标事件:mousedown
、mousemove
和mouseup
。以下是一个简单的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Draggable Element</title>
<style>
#draggable {
width: 100px;
height: 100px;
background: red;
position: absolute;
cursor: pointer;
}
</style>
</head>
<body>
<div id="draggable"></div>
<script>
const draggable = document.getElementById('draggable');
let active = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = 0;
let yOffset = 0;
draggable.addEventListener('mousedown', dragStart, false);
document.addEventListener('mouseup', dragEnd, false);
document.addEventListener('mousemove', drag, false);
function dragStart(e) {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
if (e.target === draggable) {
active = true;
}
}
function dragEnd(e) {
initialX = currentX;
initialY = currentY;
active = false;
}
function drag(e) {
if (active) {
e.preventDefault();
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, draggable);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
</script>
</body>
</html>
在这个例子中,我们有一个可拖拽的div
元素,其ID为draggable
。我们为它添加了mousedown
、mouseup
和mousemove
事件监听器。dragStart
函数记录鼠标点击的位置,并设置一个标志active
来指示拖拽开始。dragEnd
函数结束拖拽操作。drag
函数在拖拽时更新元素的位置。我们使用transform
属性通过setTranslate
函数来实际移动元素。
评论已关闭