js 实现拖拽效果
在JavaScript中实现拖拽效果通常涉及监听鼠标事件并更新元素的位置。以下是一个简单的实现示例:
HTML:
<div id="draggable" style="width: 100px; height: 100px; background: red; position: absolute; cursor: pointer;"></div>
JavaScript:
var dragItem = document.getElementById('draggable');
var active = false;
var currentX;
var currentY;
var initialX;
var initialY;
var xOffset = 0;
var yOffset = 0;
dragItem.addEventListener('mousedown', function(event) {
initialX = event.clientX - xOffset;
initialY = event.clientY - yOffset;
if (event.target === dragItem) {
active = true;
}
});
document.addEventListener('mouseup', function() {
active = false;
});
document.addEventListener('mousemove', function(event) {
if (active) {
currentX = event.clientX - initialX;
currentY = event.clientY - initialY;
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, dragItem);
}
});
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
这段代码实现了一个可拖拽的红色方块。当用户点击方块时,mousedown
事件被触发,并记录下鼠标相对元素位置的偏移量。随后在 mousemove
事件中更新元素的位置。当用户释放鼠标按钮时,mouseup
事件被触发,停止拖拽操作。
评论已关闭