使用js写一个鼠标框选的效果
鼠标框选效果通常指的是用户在页面上拖动鼠标时,可以框选一个区域,并高亮显示这个区域。以下是一个简单的示例,使用原生JavaScript来实现这个效果:
- HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>鼠标框选效果</title>
<style>
#selection-box {
position: absolute;
border: 1px dashed #000;
background-color: rgba(0, 255, 0, 0.1);
display: none;
pointer-events: none;
z-index: 9999;
}
</style>
</head>
<body>
<div id="content">
<!-- 这里是页面的主要内容 -->
<p>请在此区域内拖动鼠标进行框选</p>
</div>
<div id="selection-box"></div>
<script src="script.js"></script>
</body>
</html>
- JavaScript (
script.js
文件):
document.addEventListener('DOMContentLoaded', function() {
let startX, startY, endX, endY, isDragging = false;
const selectionBox = document.getElementById('selection-box');
const content = document.getElementById('content');
function updateSelectionBox() {
if (!isDragging) return;
selectionBox.style.left = Math.min(startX, endX) + 'px';
selectionBox.style.top = Math.min(startY, endY) + 'px';
selectionBox.style.width = Math.abs(endX - startX) + 'px';
selectionBox.style.height = Math.abs(endY - startY) + 'px';
selectionBox.style.display = 'block';
}
content.addEventListener('mousedown', function(e) {
startX = e.pageX - content.offsetLeft;
startY = e.pageY - content.offsetTop;
isDragging = true;
selectionBox.style.display = 'block';
});
content.addEventListener('mousemove', function(e) {
if (!isDragging) return;
endX = e.pageX - content.offsetLeft;
endY = e.pageY - content.offsetTop;
updateSelectionBox();
});
content.addEventListener('mouseup', function() {
isDragging = false;
// 你可以在这里添加处理框选完成后的逻辑,例如获取框选的元素等。
// 例如:console.log('框选完成', startX, startY, endX, endY);
// 隐藏选择框,如果需要的话也可以不隐藏,以便查看框选区域。
selectionBox.style.display = 'none';
});
});
这个示例中,当用户在 #content
区域内拖动鼠标时,会显示一个选择框,框的大小会随着鼠标的移动而动态变化。当用户释放鼠标时,框选完成,并且可以在此处添加处理框选完成后的逻辑。