用js 写一个 监听鼠标点击要排序的对象,跟随鼠标移动进行上下排序,鼠标释放后排序结束。
时间: 2023-07-20 10:08:39 浏览: 54
可以使用jQuery实现这个操作,具体步骤如下:
1. 给要排序的对象绑定 mousedown、mousemove、mouseup 事件,分别对应按下、移动、释放鼠标时的操作。
2. 在 mousedown 事件中记录当前点击的元素及其位置,并将其设置为可拖拽状态。
3. 在 mousemove 事件中,根据鼠标位置实时计算当前元素应该出现的位置,并将其进行排序。
4. 在 mouseup 事件中,取消元素的可拖拽状态,结束排序。
代码如下:
```javascript
$(function() {
var isDragging = false; // 是否正在拖拽
var $draggingItem = null; // 当前正在拖拽的元素
var startY = 0; // 记录元素初始位置
// 绑定 mousedown 事件
$('.sort-item').on('mousedown', function(e) {
isDragging = true;
$draggingItem = $(this);
startY = e.pageY - $draggingItem.index() * $draggingItem.outerHeight();
$draggingItem.addClass('dragging');
});
// 绑定 mousemove 事件
$(document).on('mousemove', function(e) {
if (!isDragging) return;
var newIndex = Math.round((e.pageY - startY) / $draggingItem.outerHeight());
if (newIndex < 0) newIndex = 0;
if (newIndex >= $('.sort-item').length) newIndex = $('.sort-item').length - 1;
if (newIndex !== $draggingItem.index()) {
$('.sort-item').eq(newIndex).before($draggingItem);
}
});
// 绑定 mouseup 事件
$(document).on('mouseup', function(e) {
if (!isDragging) return;
isDragging = false;
$draggingItem.removeClass('dragging');
$draggingItem = null;
});
});
```
需要注意的是,这里使用了 CSS 类名来标记当前正在拖拽的元素,并通过 `before` 方法实现了排序。同时,为了避免鼠标移动过快导致元素跳动,这里使用了 `Math.round` 方法进行四舍五入处理。