js怎么实现滑动选取
滑动选取实现方法
监听鼠标事件
通过监听 mousedown、mousemove 和 mouseup 事件实现滑动选取功能。在 mousedown 时记录起始位置,mousemove 时计算选区范围,mouseup 时结束选取。
let isSelecting = false;
let startX, startY;
document.addEventListener('mousedown', (e) => {
isSelecting = true;
startX = e.clientX;
startY = e.clientY;
});
document.addEventListener('mousemove', (e) => {
if (!isSelecting) return;
const currentX = e.clientX;
const currentY = e.clientY;
const width = currentX - startX;
const height = currentY - startY;
// 更新选区样式或逻辑
});
document.addEventListener('mouseup', () => {
isSelecting = false;
});
绘制选区框
动态创建一个 div 元素作为选区框,通过 CSS 设置边框和半透明背景。
const selectionBox = document.createElement('div');
selectionBox.style.position = 'absolute';
selectionBox.style.border = '2px dashed #000';
selectionBox.style.backgroundColor = 'rgba(0, 0, 255, 0.1)';
document.body.appendChild(selectionBox);
// 在 mousemove 中更新选区框位置和尺寸
selectionBox.style.left = `${Math.min(startX, currentX)}px`;
selectionBox.style.top = `${Math.min(startY, currentY)}px`;
selectionBox.style.width = `${Math.abs(width)}px`;
selectionBox.style.height = `${Math.abs(height)}px`;
检测元素碰撞
通过比较元素位置与选区框的范围,判断是否被选中。
function isElementInSelection(element, selectionBox) {
const rect = element.getBoundingClientRect();
const boxRect = selectionBox.getBoundingClientRect();
return !(
rect.right < boxRect.left ||
rect.left > boxRect.right ||
rect.bottom < boxRect.top ||
rect.top > boxRect.bottom
);
}
// 遍历所有目标元素检测碰撞
document.querySelectorAll('.selectable').forEach(el => {
if (isElementInSelection(el, selectionBox)) {
el.classList.add('selected');
} else {
el.classList.remove('selected');
}
});
优化性能
对于大量元素,使用 requestAnimationFrame 节流 mousemove 事件。
let rafId;
document.addEventListener('mousemove', (e) => {
if (!isSelecting) return;
cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(() => {
// 更新选区逻辑
});
});
触摸屏支持
添加 touchstart、touchmove 和 touchend 事件监听以实现移动端兼容。
document.addEventListener('touchstart', (e) => {
isSelecting = true;
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
});
document.addEventListener('touchmove', (e) => {
if (!isSelecting) return;
const currentX = e.touches[0].clientX;
const currentY = e.touches[0].clientY;
// 更新选区逻辑
});
清除选区
在 mouseup 或 touchend 后移除选区框,或保留选择状态。

document.addEventListener('mouseup', () => {
isSelecting = false;
selectionBox.style.display = 'none';
});
以上方法组合可实现基础滑动选取功能,可根据实际需求调整样式和交互逻辑。






