我找到了一個解決方案。計算所有放置區域的中心之間的距離,並在'dragmove'回調中拖動div,並將類添加到最近的放置區域。 然後,使用'dynamicdrop'屬性來激活所需的dropzone。這個過程通過dragmove持續發生。
$('.allowDrop').removeClass('allowDrop');
var distArr = [];
var elemPos = event.target.getBoundingClientRect();
var elemCenter = {};
elemCenter.x = (elemPos.top + elemPos.bottom)/2;
elemCenter.y = (elemPos.left + elemPos.right)/2;
$('.js-drop').each(function(index, el) {
var dropPos = el.getBoundingClientRect();
var dropCenter = {};
dropCenter.x = (dropPos.top + dropPos.bottom)/2;
dropCenter.y = (dropPos.left + dropPos.right)/2;
var distance = Math.sqrt(Math.pow((elemCenter.x - dropCenter.x),2) +
Math.pow((elemCenter.y - dropCenter.y),2));
distArr.push(distance);
})
var minDist = Math.min.apply(Math, distArr);
var index = distArr.indexOf(minDist);
$($('.js-drop')[index]).addClass('allowDrop');
// setup drop areas.
setupRemoveZone('.removeShape', '.js-drag');
setupDropzone('.allowDrop', '.js-drag');
interact.dynamicDrop(true);