一、 知识点
- 设置被拖拽的元素draggable为true (HTML5新特性)
- 关键方法:void dataTransfer.setDragImage(img, xOffset, yOffset);
- 注意点:Note: If the [
Element] is an existing [HTMLElement], it needs to be visible in the viewport in order to be shown as a drag feedback image. Alternatively, you can create a new DOM element that might be off-screen specifically for this purpose.
即若设置为自定义元素时,有两种选择,一个是可视的(display 不能为none,opacity不能为0,etc...);或者动态生成DOM。
二、 目标效果
类似VSCODE的拖拽图标

拖拽样式如图所示
二、 预设目标样式
我没有采取动态生成DOM的方式,而是采取将index的值赋为-1来作为目标样式
// css 样式
.drag-ghost {
height: 16px;
border-radius: 4px;
position: absolute;
background-color: #ffffff;
padding: 0 4px;
font-size: 13px;
z-index: -9999;
left: 0px;
top: 0px;
}
三、 js中调用dataTransfer.setDragImage
html中将二中预设的DOM的id设置为ghost
const ghost = document.getElementById('ghost');
$event.dataTransfer.setDragImage(ghost, -10, -10);
四、 最终效果

最终效果