最近在做项目时需要实现网页要素拖拽功能,下面记录一下方法。
一、实现效果
网页要素拖拽
二、JavaScript代码
const box = document.getElementById('box');
const runtimeLabel = document.getElementById('runtime');
let startX, startY; // 鼠标初始位置
let initialLeft, initialTop; // 元素初始位置
box.addEventListener('dragstart', event => {
startX = event.clientX;
startY = event.clientY;
initialLeft = box.offsetLeft;
initialTop = box.offsetTop;
offsetX = startX - initialLeft;
offsetY = startY - initialTop;
});
document.addEventListener('dragover', event => {
event.preventDefault();
const newX = event.clientX - startX + initialLeft;
const newY = event.clientY - startY + initialTop;
const maxLeft = document.documentElement.clientWidth - box.offsetWidth;
const maxTop = document.documentElement.clientHeight - box.offsetHeight;
box.style.left = `${Math.min(maxLeft, Math.max(0, newX))}px`;
box.style.top = `${Math.min(maxTop, Math.max(0, newY))}px`;
});
let totalSeconds = coordinateTime; // 假设 coordinateTime 是总秒数
let hour = Math.floor(totalSeconds / 3600);
let minute = Math.floor((totalSeconds % 3600) / 60);
let second = totalSeconds % 60;
// 将时间显示在页面上
runtimeLabel.style.whiteSpace = 'pre-wrap';
runtimeLabel.textContent = `运行时间:\n${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
三、CSS代码
#box {
width: 90px;
height: 60px;
border: 1px solid #ff00e1;
position: absolute;
left: 100px;
top: 800px;
z-index: 6001;
}
#runtime {
position: absolute;
left: 10px;
top: 10px;
color: #00FFFF;
z-index: 6001;
}