JavaScript/drag

来自康健生活
Kangkk​(留言 | 贡献)2022年4月1日 (五) 07:07的版本 (→引言)

引言

在拖动目标上触发事件 (源元素):

  • ondragstart - 开始拖动元素时触发
  • ondrag - 正在拖动元素时触发
  • ondragend - 拖动元素完成后触发

释放目标时触发的事件:

  • ondragenter - 当被鼠标拖动的对象进入其容器范围内时触发此事件
  • ondragover - 当用户将对象拖到有效的放置目标上时,连续触发目标元素
  • ondragleave - 当被鼠标拖动的对象离开其容器范围内时触发此事件
  • ondrop - 在一个拖动过程中,释放鼠标键时触发此事件

事件

ondragover

当被拖拽元素处于一个列表中,它和即将被替换的元素都被绑定 ondragover 事件。

<ul>
  <li onDragOver={e => console.log(e.target)}>被拖拽元素</li>
  <li onDragOver={e => console.log(e.target)}>被替换元素</li>
</ul>

当被拖拽元素在拖拽过程中进入到被替换元素的对象容器范围内,触发的是被替换元素的

e.dataTransfer

在做拖拽的时候,我在 onDragStart 阶段使用

_.dataTransfer.setData(format, {
  'id': _.target?.id || _.target?.getAttribute('data-id'),
  format,
  'class': className,
  'listClass': format === 'group'
    ? 'groupArtboardList'
    : void 0
});

设置一些参数,以期待在 onDragOver 阶段拿出来使用,但实际取出来的却是空值。 模板:Leftrightflex

随后查阅,有人的解释是说 dataTransfer 的存储机制是在专为 drag 设置的数据存储 stroe 有读取限制,根据 7.7 The DragEvent and DataTransfer interfaces -> the-drag-data-store[1]

The information in a drag data store used to generate the UI feedback during the drag consists of:

A list of zero or more elements.
Optionally, a bitmap image and the coordinate of a point within that image.
A drag data store is created at the start of a drag-and-drop operation in the read/write mode, and then progresses through the following three modes as the operation proceeds:

Read/write mode
At the start of the drag. New data can be added to the drag data store.

Protected mode
During the drag. The formats and kinds in the drag data store list of items representing dragged data can be enumerated, but the data itself is unavailable and no new data can be added.

Read-only mode
After the drop. The list of items representing dragged data can be read, including the data. No new data can be added.
  1. ↑ HTML5 A vocabulary and associated APIs for HTML and XHTML Editor's Draft 25 October 2010