有没有一种方法可以检测某个元素上是否拖动了某些东西?还是触发悬停事件?找到了一些有关通过onMove将类添加到拖动元素的方法,但这似乎对我不起作用。
答案 0 :(得分:1)
我用一个解决方案制作了一个JSBin:https://jsbin.com/xuwocis/edit?html,js,output
var sorting = false;
new Sortable(el, {
onStart: function() {
sorting = true;
},
onEnd: function() {
sorting = false;
// remove styling
targetElement.style.backgroundColor = '';
},
// forceFallback:true
});
// For native drag&drop
targetElement.addEventListener('dragover', function(evt) {
evt.preventDefault();
});
targetElement.addEventListener('dragenter', function(evt) {
if (sorting && !targetElement.contains(evt.relatedTarget)) {
// Here is where you add the styling of targetElement
targetElement.style.backgroundColor = 'red';
}
});
targetElement.addEventListener('dragleave', function(evt) {
if (sorting && !targetElement.contains(evt.relatedTarget)) {
// Here is where you remove the styling of targetElement
targetElement.style.backgroundColor = '';
}
});
// For fallback
targetElement.addEventListener('mouseenter', function(evt) {
if (sorting) {
// Here is where you change the styling of targetElement
targetElement.style.backgroundColor = 'red';
}
});
targetElement.addEventListener('mouseleave', function(evt) {
if (sorting) {
// Here is where you remove the styling of targetElement
targetElement.style.backgroundColor = '';
}
});
el.addEventListener('touchmove', function(evt) {
if (!sorting) { return; }
var x = evt.touches[0].clientX;
var y = evt.touches[0].clientY;
var elementAtTouchPoint = document.elementFromPoint(x, y);
if (elementAtTouchPoint === targetElement ||
// In case of a ghost element, the element at touch point
// is the ghost element and thus we need to check if the parent
// of the ghost element is the targetElement.
elementAtTouchPoint.parentNode === targetElement) {
targetElement.style.backgroundColor = 'red';
} else {
// Here is where you remove the styling of targetElement
targetElement.style.backgroundColor = '';
}
});
基本上,如果使用SortableJS进行排序,则对后备事件执行mouseenter和mouseleave事件,对于本机拖放则执行dragenter和dragleave事件(忽略气泡)。如果您没有forceFallback: true
,则两全其美。