要实现一个简单的拖拽效果,你可以创建一个可拖拽的元素,并监听鼠标事件来更新其位置。以下是一个简单的示例代码:
HTML:
<div id="draggable">拖拽我</div>
CSS:
#draggable {
width: 100px;
height: 100px;
background: #ccc;
position: absolute;
cursor: pointer;
}
JavaScript:
const draggable = document.getElementById('draggable');
let active = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = 0;
let yOffset = 0;
function dragStart(e) {
if (e.type === "touchstart") {
initialX = e.touches[0].clientX - xOffset;
initialY = e.touches[0].clientY - yOffset;
} else {
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();
if (e.type === "touchmove") {
currentX = e.touches[0].clientX - initialX;
currentY = e.touches[0].clientY - initialY;
} else {
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)";
}
// Attach events
draggable.addEventListener('mousedown', dragStart);
draggable.addEventListener('touchstart', dragStart);
document.addEventListener('mousemove', drag);
document.addEventListener('touchmove', drag);
document.addEventListener('mouseup', dragEnd);
document.addEventListener('touchend', dragEnd);
document.addEventListener('mouseleave', dragEnd);
这段代码实现了一个可以通过鼠标或触摸移动的拖拽效果。当你拖动元素时,它会跟随你的鼠标或触摸点移动。代码中使用了transform: translate3d()
来改变元素的位置,这样可以提升性能,特别是在处理大量元素的情况下。