jQuery 拖拽选择(Drag and Drop Selection)是一种用户界面交互技术,允许用户通过拖动鼠标来选择屏幕上的元素。这种技术广泛应用于各种应用程序,如文件管理器、绘图工具、数据可视化等。
以下是一个简单的 jQuery 拖拽选择示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Drag and Drop Selection</title>
<style>
.selectable {
width: 300px;
height: 200px;
border: 1px solid #ccc;
position: relative;
}
.selectable div {
width: 50px;
height: 50px;
background-color: #f0f0f0;
border: 1px solid #ccc;
position: absolute;
}
.selected {
background-color: #add8e6;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="selectable">
<div style="left: 10px; top: 10px;"></div>
<div style="left: 70px; top: 10px;"></div>
<div style="left: 130px; top: 10px;"></div>
<div style="left: 190px; top: 10px;"></div>
<div style="left: 10px; top: 70px;"></div>
<div style="left: 70px; top: 70px;"></div>
<div style="left: 130px; top: 70px;"></div>
<div style="left: 190px; top: 70px;"></div>
</div>
<script>
$(document).ready(function() {
var startX, startY, isDragging = false;
var $selectable = $('.selectable');
var $selected = [];
$selectable.on('mousedown', function(e) {
startX = e.pageX - $selectable.offset().left;
startY = e.pageY - $selectable.offset().top;
isDragging = true;
});
$(document).on('mousemove', function(e) {
if (isDragging) {
var endX = e.pageX - $selectable.offset().left;
var endY = e.pageY - $selectable.offset().top;
$selectable.find('div').each(function() {
var $this = $(this);
var offset = $this.offset();
var left = offset.left - $selectable.offset().left;
var top = offset.top - $selectable.offset().top;
if (left >= startX && left <= endX && top >= startY && top <= endY) {
$this.addClass('selected');
if (!$selected.includes($this)) {
$selected.push($this);
}
} else {
$this.removeClass('selected');
var index = $selected.indexOf($this);
if (index > -1) {
$selected.splice(index, 1);
}
}
});
}
});
$(document).on('mouseup', function() {
isDragging = false;
});
});
</script>
</body>
</html>
mousemove
事件中正确计算鼠标位置和元素位置,并更新选择区域。selected
类导致的重绘。requestAnimationFrame
来优化 mousemove
事件的处理,减少重绘次数。jquery-touchswipe
来处理触摸事件。通过以上方法,可以有效地实现和优化 jQuery 拖拽选择功能。
领取专属 10元无门槛券
手把手带您无忧上云