我正在使用 html5 的拖放功能在屏幕上重新排列 dom 元素 - 当我这样做时,我将 css 行为附加到拖放的各种状态,但我遇到的问题是即使在我之后悬停状态仍然存在已从 DOM 元素中拖放、鼠标移出。这是我的代码:
JAVASCRIPT:
function addDragListeners(){
$('.segmentListItem').each(function(index){
$(this)[0].addEventListener('dragstart',handleDragStart,false); //rollover for current
$(this)[0].addEventListener('drop',handleDrop,false); //drops dragged element
$(this)[0].addEventListener('dragover',handleDragOver,false); //allows us to drop
$(this)[0].addEventListener('dragenter',handleDragEnter,false); //rollover for target
$(this)[0].addEventListener('dragleave',handleDragLeave,false); //sets dragged item back to normal
$(this)[0].addEventListener('dragend',handleDragEnd,false); //sets all back to normal
});
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over'); // this / e.target is previous target element.
}
function handleDragEnd(e){
$('.segmentListItem').removeClass('over'); //removes the over class on all elements
}
function handleDragStart(e){
draggedItem = this;
e.dataTransfer.effectAllowed = 'move';
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
return false;
}
function handleDrop(e){
if (e.stopPropagation) {
e.stopPropagation();
}
if (draggedItem != this) { //MH - swap if we're not dragging the item onto itself
var draggedIndex = $('.segmentListItem').index($(draggedItem));
var targetIndex = $('.segmentListItem').index($(this));
if (draggedIndex > targetIndex){
$(draggedItem).insertBefore($(this));
} else {
$(draggedItem).insertAfter($(this));
}
}
return false;
}
CSS:
a { border-radius: 10px; }
a:hover { background: #ccc; }
.segmentListItem { text-align:center; width: 50px; margin-right: 5px; font-size: 16px; display:inline-block; cursor:move; padding:10px; background: #fff; user-select: none; }
.segmentListItem.over { background: #000; color: #fff; }