js实现鼠标拖拽多选功能
在JavaScript中实现一个基本的鼠标拖拽多选功能,可以通过监听鼠标事件来完成。以下是一个简单的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag Select</title>
<style>
.select-area {
width: 400px;
height: 200px;
position: relative;
border: 1px solid #000;
}
.select-box {
background: rgba(0, 0, 255, 0.3);
position: absolute;
border: 1px dashed #000;
pointer-events: none;
}
.item {
width: 100px;
height: 50px;
position: absolute;
top: 0;
left: 0;
border: 1px solid #000;
margin: 10px;
}
</style>
</head>
<body>
<div class="select-area">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<!-- More items here -->
</div>
<script>
const selectArea = document.querySelector('.select-area');
let startX, startY, isDragging = false;
selectArea.addEventListener('mousedown', function(e) {
startX = e.pageX - this.offsetLeft;
startY = e.pageY - this.offsetTop;
isDragging = true;
const selectBox = document.createElement('div');
selectBox.classList.add('select-box');
selectArea.appendChild(selectBox);
});
selectArea.addEventListener('mousemove', function(e) {
if (isDragging) {
const selectBox = this.querySelector('.select-box');
const x = Math.min(e.pageX - this.offsetLeft, startX);
const y = Math.min(e.pageY - this.offsetTop, startY);
const width = Math.abs(e.pageX - this.offsetLeft - startX);
const height = Math.abs(e.pageY - this.offsetTop - startY);
selectBox.style.left = `${x}px`;
selectBox.style.top = `${y}px`;
selectBox.style.width = `${width}px`;
selectBox.style.height = `${height}px`;
// 选中交集中的所有项
const items = this.querySelectorAll('.item');
items.forEach(item => {
const itemRect = item.getBoundingClientRect();
if (x < itemRect.left && itemRect.left < x + width
&& y < itemRect.top && itemRect.top < y + height) {
item.classList.add('selected'); // 添加自定义的selected类来标记选中
} else {
item.classList.remove('selected');
}
});
}
});
selectArea.addEventListener('mouseup', function() {
isDragging = false;
const selectBox = this.querySelector('.select-box');
if (selectBox) {
selectArea.removeChild(selectBox);
}
});
</script>
</body>
</html>
在这个例子中,当
评论已关闭