[英]Custom drag drop implementation
我正在推出一個自定義拖放實現,它是 Dragula 庫的簡化版本。 這是我的小提琴:
帶德拉古拉: http://jsfiddle.net/8m4jrfwn/
使用我的自定義拖放實現: http://jsfiddle.net/7wLtojs4/1/
我看到的問題是我的自定義拖放實現有點自由。 我希望用戶只能使用 class 框放在另一個 div 的頂部或底部。 我怎樣才能做到這一點? 代碼在這里:
function handleMouseDown(e) {
window.dragging = {};
dragging.pageX = e.pageX;
dragging.pageY = e.pageY;
dragging.elem = this;
dragging.offset = $(this).offset();
$('body')
.on('mouseup', handleMouseUp)
.on('mousemove', handleDragging);
}
function handleDragging(e) {
let left = dragging.offset.left + (e.pageX - dragging.pageX);
let top = dragging.offset.top + (e.pageY - dragging.pageY);
$(dragging.elem)
.offset({top: top, left: left});
}
function handleMouseUp() {
$('body')
.off('mousemove', handleDragging)
.off('mouseup', handleMouseUp);
}
let boxElement = '.item';
$(boxElement).mousedown(handleMouseDown);
我在這里沒有看到任何關於 mouseup 事件會發生什么的邏輯。 似乎您需要在 mouseup 上檢測元素的新順序,然后交換它們的位置。
為此,您應該知道所有人的位置。 在 mouseup 上,您可以根據新位置對它們重新排序。
在我的實現中( https://jsfiddle.net/jaromudr/c99oueg5/ )我使用了下一個邏輯:
onMove(draggable) {
const sortedDraggables = this.getSortedDraggables()
const pinnedPositions = sortedDraggables.map((draggable) => draggable.pinnedPosition)
const currentIndex = sortedDraggables.indexOf(draggable)
const targetIndex = indexOfNearestPoint(pinnedPositions, draggable.position, this.options.radius, getYDifference)
if (targetIndex !== -1 && currentIndex !== targetIndex) {
arrayMove(sortedDraggables, currentIndex, targetIndex)
this.bubling(sortedDraggables, draggable)
}
}
bubling(sortedDraggables, currentDraggable) {
const currentPosition = this.startPosition.clone()
sortedDraggables.forEach((draggable) => {
if (!draggable.pinnedPosition.compare(currentPosition)) {
if (draggable === currentDraggable && !currentDraggable.nativeDragAndDrop) {
draggable.pinnedPosition = currentPosition.clone()
} else {
draggable.pinPosition(currentPosition, (draggable === currentDraggable) ? 0 : this.options.timeExcange)
}
}
currentPosition.y = currentPosition.y + draggable.getSize().y + this.verticalGap
})
}
在移動中,我們檢測列表中的 position 是否已更改,並將其他draggables
對象移動到新位置。
在拖動結束時,我們只需將 currentDraggable 移動到 pinnedPosition
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.