我正在努力改进拖放实现,方法是创建一个指示器(拖曳元素的轮廓),当您在网格中拖动和移动时,该指示器会沿着设置的柔性网格移动。在当前实现中,拖动的元素就位,当我放下放置目标时,它会更新flex命令。我要做的是完全隐藏元素,以提供关于元素放置位置的更好的视觉提示。问题是如果我在拖动开始时隐藏元素,拖动工作流突然结束,甚至不会触发后续的拖动操作。
答案 0 :(得分:8)
如果我正确理解您的问题,您希望在拖动操作期间隐藏被拖动的元素。这可以通过在触发dragover事件时隐藏元素来完成。这是一个例子:
JSFiddle(拖动橙色框)
使用Javascript:
;
(function($, undefined) {
var dragging;
$(function() {
$('div.flex-grid').on({
'dragstart': dragstart,
'dragend': dragend
}, 'div.drag').on({
'dragover dragenter': dragover,
'dragleave': dragleave,
'drop': drop
}, 'div.drop');
});
function dragstart(e) {
e.stopPropagation();
var dt = e.originalEvent.dataTransfer;
if (dt) {
dt.effectAllowed = 'move';
dt.setData('text/html', '');
dragging = $(this);
}
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
if (dt && dragging) {
dt.dropEffect = 'move';
$(this).css({
'background-color': 'yellow'
});
dragging.hide();
}
return false;
}
function dragleave(e) {
e.stopPropagation();
$(this).css({
'background-color': '#fff'
});
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
if (dragging) {
var dropzone = $(this);
dragging.data('dropzone', dropzone);
dragging.trigger('dragend');
}
return false;
}
function dragend(e) {
if (dragging) {
var dropzone = dragging.data('dropzone');
if (dropzone) {
dropzone.append(dragging);
}
dragging.show();
}
$('div.drop').css({
'background-color': '#fff'
});
dragging = undefined;
}
}(jQuery));
HTML:
<div class="flex-grid">
<div class="flex-row">
<div class="drop">
<div class="drag" draggable="true"></div>
</div>
<div class="drop"></div>
<div class="drop"></div>
</div>
<div class="flex-row">
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
</div>
<div class="flex-row">
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
</div>
</div>
CSS:
* {
border-style: none;
padding: 0;
margin: 0;
}
.flex-grid {
display: flex;
display: -webkit-flex;
flex-direction: column;
-webkit-flex-direction: column;
}
.flex-row {
display: flex;
display: -webkit-flex;
flex-direction: row;
-webkit-flex-direction: row;
}
.drop,
.drag {
display: block;
width: 100px;
height: 100px;
}
.drag {
background-color: orange;
cursor: move;
}
.drop {
border: 1px solid #ccc;
background-color: #fff;
}