1. 6.11 Drag and drop
      1. 6.11.1 Introduction
      2. 6.11.2 The drag data store
      3. 6.11.3 The DataTransfer interface
        1. 6.11.3.1 The DataTransferItemList interface
        2. 6.11.3.2 The DataTransferItem interface
      4. 6.11.4 The DragEvent interface
      5. 6.11.5 Processing model
      6. 6.11.6 Events summary
      7. 6.11.7 The draggable attribute
      8. 6.11.8 Security risks in the drag-and-drop model

6.11 Drag and drop

HTML_Drag_and_Drop_API

Support in all current engines.

Firefox3.5+Safari3.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)18Internet Explorer5.5+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android4.4+Samsung Internet1.5+Opera Android14+

このセクションは、イベントベースのドラッグアンドドロップのメカニズムを定義する。

この仕様は、ドラッグアンドドロップ操作が実際に何であるかを正確に定義しない。

ポインティングデバイスをもつ視覚メディア上に、ドラッグ操作は一連のmousemoveイベントが続くmousedownイベントのデフォルトアクションであるかもしれず、ドロップは解放されているマウスによって引き起こされるかもしれない。

ポインティングデバイス以外の入力モダリティを使用する場合、ユーザーはおそらくドラッグアンドドロップ操作を実行するために明示的に意思表示する必要があり、それらがドラッグを望み、ドロップを望む場所を、それぞれ主張する。

However it is implemented, drag-and-drop operations must have a starting point (e.g. where the mouse was clicked, or the start of the selection or element that was selected for the drag), may have any number of intermediate steps (elements that the mouse moves over during a drag, or elements that the user picks as possible drop points as they cycle through possibilities), and must either have an end point (the element above which the mouse button was released, or the element that was finally selected), or be canceled. The end point must be the last element selected as a possible drop point before the drop occurs (so if the operation is not canceled, there must be at least one element in the middle step).

6.11.1 Introduction

この節は非規範的である。

要素をドラッグ可能にするためには、要素にdraggable属性を与え、ドラッグされているデータを格納するdragstartドラッグに対してイベントリスナーを設定する。

イベントハンドラーは典型的に、それがドラッグされているテキスト選択でないことをチェックする必要があり、次にDataTransferオブジェクトにデータを格納し、許可される効果(コピー、移動、リンク、またはいくつかの組み合わせ)を設定する必要がある。

たとえば:

<p>What fruits do you like?</p>
<ol ondragstart="dragStartHandler(event)">
 <li draggable="true" data-value="fruit-apple">Apples</li>
 <li draggable="true" data-value="fruit-orange">Oranges</li>
 <li draggable="true" data-value="fruit-pear">Pears</li>
</ol>
<script>
  var internalDNDType = 'text/x-example'; // set this to something specific to your site
  function dragStartHandler(event) {
    if (event.target instanceof HTMLLIElement) {
      // use the element's data-value="" attribute as the value to be moving:
      event.dataTransfer.setData(internalDNDType, event.target.dataset.value);
      event.dataTransfer.effectAllowed = 'move'; // only allow moves
    } else {
      event.preventDefault(); // don't allow selection to be dragged
    }
  }
</script>

ドロップを受け入れるために、次のイベントをリッスンする必要がある:

  1. dragenterイベントハンドラーは、イベントをキャンセルすることによって、ドロップターゲットが潜在的にドロップを受け入れる可能性があるかどうかを報告する。
  2. dragoverイベントハンドラーは、イベントに関連付けられたDataTransferdropEffect属性を設定することによって、ユーザーに表示されるフィードバックを指定する。このイベントはまたキャンセルする必要がある。
  3. dropイベントハンドラーは、ドロップを受け入れるまたは拒否する最終選択を持つ。ドロップが受け入れられる場合、イベントハンドラーはターゲットに対してドロップ操作を実行しなければならない。このイベントはキャンセルする必要があるため、dropEffect属性の値をソースによって使用できるようにする。そうでなければ、ドロップ操作は拒否される。

たとえば:

<p>Drop your favorite fruits below:</p>
<ol ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)"
    ondrop="dropHandler(event)">
</ol>
<script>
  var internalDNDType = 'text/x-example'; // set this to something specific to your site
  function dragEnterHandler(event) {
    var items = event.dataTransfer.items;
    for (var i = 0; i < items.length; ++i) {
      var item = items[i];
      if (item.kind == 'string' && item.type == internalDNDType) {
        event.preventDefault();
        return;
      }
    }
  }
  function dragOverHandler(event) {
    event.dataTransfer.dropEffect = 'move';
    event.preventDefault();
  }
  function dropHandler(event) {
    var li = document.createElement('li');
    var data = event.dataTransfer.getData(internalDNDType);
    if (data == 'fruit-apple') {
      li.textContent = 'Apples';
    } else if (data == 'fruit-orange') {
      li.textContent = 'Oranges';
    } else if (data == 'fruit-pear') {
      li.textContent = 'Pears';
    } else {
      li.textContent = 'Unknown Fruit';
    }
    event.target.appendChild(li);
  }
</script>

ディスプレイからオリジナルの要素(ドラッグされたもの)を削除するために、dragendイベントを使用できる。

ここで私たちの例のために、それはそのイベントを処理するために元のマークアップを更新することを意味する:

<p>What fruits do you like?</p>
<ol ondragstart="dragStartHandler(event)" ondragend="dragEndHandler(event)">
 ...as before...
</ol>
<script>
  function dragStartHandler(event) {
    // ...as before...
  }
  function dragEndHandler(event) {
    if (event.dataTransfer.dropEffect == 'move') {
      // remove the dragged element
      event.target.parentNode.removeChild(event.target);
    }
  }
</script>

6.11.2 The drag data store

ドラッグデータストアとして知られる、ドラッグアンドドロップ操作を支えるデータは次の情報で構成される:

ドラッグデータストア作成された場合、それはそのドラッグデータストアアイテムリストが空であるように初期化されなければならず、それはドラッグデータストアのデフォルトフィードバックを持たず、ドラッグデータストアのビットマップおよびドラッグデータストアのホットスポット座標を持たず、そのドラッグデータストアモード保護モードであり、そのドラッグデータストアの許可された効果の状態は文字列"uninitialized"である。

6.11.3 The DataTransfer interface

DataTransfer

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12+

DataTransferオブジェクトは、ドラッグアンドドロップ操作を支えるドラッグデータストアを公開するために使用される。

[Exposed=Window]
interface DataTransfer {
  constructor();

  attribute DOMString dropEffect;
  attribute DOMString effectAllowed;

  [SameObject] readonly attribute DataTransferItemList items;

  undefined setDragImage(Element image, long x, long y);

  /* old interface */
  readonly attribute FrozenArray<DOMString> types;
  DOMString getData(DOMString format);
  undefined setData(DOMString format, DOMString data);
  undefined clearData(optional DOMString format);
  [SameObject] readonly attribute FileList files;
};
dataTransfer = new DataTransfer()

DataTransfer/DataTransfer

Support in all current engines.

Firefox62+Safari14.1+Chrome59+
Opera?Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet8.0+Opera Android44+

空のドラッグデータストアをもつ新しいDataTransferオブジェクトを作成する。

dataTransfer.dropEffect [ = value ]

DataTransfer/dropEffect

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

現在選択されている操作の種類を返す。操作の種類がeffectAllowed属性によって許可されるものの1つでない場合、操作は失敗する。

選択した操作を変更す設定が可能である。

可能な値は、"none"、"copy"、"link"、および"move"である。

dataTransfer.effectAllowed [ = value ]

DataTransfer/effectAllowed

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

許可される操作の種類を返す。

許可される操作を変更するために、(dragstartイベント中に)設定可能である。

可能な値は、"none"、"copy"、"copyLink"、"copyMove"、"link"、"linkMove"、"move"、"all"、および"uninitialized"である。

dataTransfer.items

DataTransfer/items

Support in all current engines.

Firefox50+Safari11.1+Chrome3+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android52+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12+

ドラッグデータとともに、DataTransferItemListオブジェクトを返す。

dataTransfer.setDragImage(element, x, y)

DataTransfer/setDragImage

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

以前に指定されたフィードバックを置換し、ドラッグフィードバックを更新するために指定された要素を使用する。

dataTransfer.types

DataTransfer/types

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

dragstartイベントで設定されたフォーマットを列挙する凍結された配列を返す。さらに、任意のファイルがドラッグされている場合、型の1つは文字列"Files"となる。

data = dataTransfer.getData(format)

DataTransfer/getData

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

指定されたデータを返す。そのようなデータが存在しない場合、空の文字列を返す。

dataTransfer.setData(format, data)

DataTransfer/setData

Support in all current engines.

Firefox3.5+Safari5+Chrome3+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android12+

指定されたデータを追加する。

dataTransfer.clearData([ format ])

DataTransfer/clearData

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

指定した書式のデータを削除する。引数が省略された場合、すべてのデータを削除する。

dataTransfer.files

DataTransfer/files

Support in all current engines.

Firefox3.6+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

もしあれば、ドラッグされているファイルのFileListを返す。

DataTransfer objects that are created as part of drag-and-drop events are only valid while those events are being fired.

A DataTransfer object is associated with a drag data store while it is valid.

A DataTransfer object has an associated types array, which is a FrozenArray<DOMString>, initially empty. When the contents of the DataTransfer object's drag data store item list change, or when the DataTransfer object becomes no longer associated with a drag data store, run the following steps:

  1. Let L be an empty sequence.

  2. If the DataTransfer object is still associated with a drag data store, then:

    1. For each item in the DataTransfer object's drag data store item list whose kind is text, add an entry to L consisting of the item's type string.

    2. If there are any items in the DataTransfer object's drag data store item list whose kind is File, then add an entry to L consisting of the string "Files". (This value can be distinguished from the other values because it is not lowercase.)

  3. Set the DataTransfer object's types array to the result of creating a frozen array from L.

The DataTransfer() constructor, when invoked, must return a newly created DataTransfer object initialized as follows:

  1. Set the drag data store's item list to be an empty list.

  2. Set the drag data store's mode to read/write mode.

  3. Set the dropEffect and effectAllowed to "none".

The dropEffect attribute controls the drag-and-drop feedback that the user is given during a drag-and-drop operation. When the DataTransfer object is created, the dropEffect attribute is set to a string value. On getting, it must return its current value. On setting, if the new value is one of "none", "copy", "link", or "move", then the attribute's current value must be set to the new value. Other values must be ignored.

The effectAllowed attribute is used in the drag-and-drop processing model to initialize the dropEffect attribute during the dragenter and dragover events. When the DataTransfer object is created, the effectAllowed attribute is set to a string value. On getting, it must return its current value. On setting, if drag data store's mode is the read/write mode and the new value is one of "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", or "uninitialized", then the attribute's current value must be set to the new value. Otherwise, it must be left unchanged.

The items attribute must return a DataTransferItemList object associated with the DataTransfer object.

The setDragImage(image, x, y) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.

  2. If the drag data store's mode is not the read/write mode, return. Nothing happens.

  3. If image is an img element, then set the drag data store bitmap to the element's image (at its natural size); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified).

  4. Set the drag data store hot spot coordinate to the given x, y coordinate.

The types attribute must return this DataTransfer object's types array.

The getData(format) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, then return the empty string.

  2. If the drag data store's mode is the protected mode, then return the empty string.

  3. Let format be the first argument, converted to ASCII lowercase.

  4. Let convert-to-URL be false.

  5. If format equals "text", change it to "text/plain".

  6. If format equals "url", change it to "text/uri-list" and set convert-to-URL to true.

  7. If there is no item in the drag data store item list whose kind is text and whose type string is equal to format, return the empty string.

  8. Let result be the data of the item in the drag data store item list whose kind is Plain Unicode string and whose type string is equal to format.

  9. If convert-to-URL is true, then parse result as appropriate for text/uri-list data, and then set result to the first URL from the list, if any, or the empty string otherwise. [RFC2483]

  10. Return result.

The setData(format, data) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.

  2. If the drag data store's mode is not the read/write mode, return. Nothing happens.

  3. Let format be the first argument, converted to ASCII lowercase.

  4. If format equals "text", change it to "text/plain".

    If format equals "url", change it to "text/uri-list".

  5. Remove the item in the drag data store item list whose kind is text and whose type string is equal to format, if there is one.

  6. Add an item to the drag data store item list whose kind is text, whose type string is equal to format, and whose data is the string given by the method's second argument.

The clearData(format) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.

  2. If the drag data store's mode is not the read/write mode, return. Nothing happens.

  3. If the method was called with no arguments, remove each item in the drag data store item list whose kind is Plain Unicode string, and return.

  4. Set format to format, converted to ASCII lowercase.

  5. If format equals "text", change it to "text/plain".

    If format equals "url", change it to "text/uri-list".

  6. Remove the item in the drag data store item list whose kind is text and whose type string is equal to format, if there is one.

The clearData() method does not affect whether any files were included in the drag, so the types attribute's list might still not be empty after calling clearData() (it would still contain the "Files" string if any files were included in the drag).

The files attribute must return a live FileList sequence consisting of File objects representing the files found by the following steps. Furthermore, for a given FileList object and a given underlying file, the same File object must be used each time.

  1. Start with an empty list L.

  2. If the DataTransfer object is no longer associated with a drag data store, the FileList is empty. Return the empty list L.

  3. If the drag data store's mode is the protected mode, return the empty list L.

  4. For each item in the drag data store item list whose kind is File, add the item's data (the file, in particular its name and contents, as well as its type) to the list L.

  5. The files found by these steps are those in the list L.

This version of the API does not expose the types of the files during the drag.

6.11.3.1 The DataTransferItemList interface

DataTransferItemList

Support in all current engines.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

DataTransferオブジェクトはDataTransferItemListオブジェクトに関連付けられる。

[Exposed=Window]
interface DataTransferItemList {
  readonly attribute unsigned long length;
  getter DataTransferItem (unsigned long index);
  DataTransferItem? add(DOMString data, DOMString type);
  DataTransferItem? add(File data);
  undefined remove(unsigned long index);
  undefined clear();
};
items.length

DataTransferItemList/length

Support in all current engines.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

ドラッグデータストア内のアイテムの数を返す。

items[index]

ドラッグデータストア内のindex番目のエントリを表すDataTransferItemオブジェクトを返す。

items.remove(index)

DataTransferItemList/remove

Support in all current engines.

Firefox50+Safari6+Chrome31+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

ドラッグデータストア内のindex番目のエントリーを削除する。

items.clear()

DataTransferItemList/clear

Support in all current engines.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

ドラッグデータストア内のすべてのエントリーを削除する。

items.add(data)

DataTransferItemList/add

Support in all current engines.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+
items.add(data, type)

ドラッグデータストアに指定されたデータに対する新しいエントリーを追加する。データがプレーンテキストである場合、type文字列も提供される必要がある。

While the DataTransferItemList object's DataTransfer object is associated with a drag data store, the DataTransferItemList object's mode is the same as the drag data store mode. When the DataTransferItemList object's DataTransfer object is not associated with a drag data store, the DataTransferItemList object's mode is the disabled mode. The drag data store referenced in this section (which is used only when the DataTransferItemList object is not in the disabled mode) is the drag data store with which the DataTransferItemList object's DataTransfer object is associated.

The length attribute must return zero if the object is in the disabled mode; otherwise it must return the number of items in the drag data store item list.

When a DataTransferItemList object is not in the disabled mode, its supported property indices are the indices of the drag data store item list.

To determine the value of an indexed property i of a DataTransferItemList object, the user agent must return a DataTransferItem object representing the ith item in the drag data store. The same object must be returned each time a particular item is obtained from this DataTransferItemList object. The DataTransferItem object must be associated with the same DataTransfer object as the DataTransferItemList object when it is first created.

The add() method must run the following steps:

  1. If the DataTransferItemList object is not in the read/write mode, return null.

  2. Jump to the appropriate set of steps from the following list:

    If the first argument to the method is a string

    If there is already an item in the drag data store item list whose kind is text and whose type string is equal to the value of the method's second argument, converted to ASCII lowercase, then throw a "NotSupportedError" DOMException.

    Otherwise, add an item to the drag data store item list whose kind is text, whose type string is equal to the value of the method's second argument, converted to ASCII lowercase, and whose data is the string given by the method's first argument.

    If the first argument to the method is a File

    Add an item to the drag data store item list whose kind is File, whose type string is the type of the File, converted to ASCII lowercase, and whose data is the same as the File's data.

  3. Determine the value of the indexed property corresponding to the newly added item, and return that value (a newly created DataTransferItem object).

The remove(index) method must run these steps:

  1. If the DataTransferItemList object is not in the read/write mode, throw an "InvalidStateError" DOMException.

  2. If the drag data store does not contain an indexth item, then return.

  3. Remove the indexth item from the drag data store.

The clear() method, if the DataTransferItemList object is in the read/write mode, must remove all the items from the drag data store. Otherwise, it must do nothing.

6.11.3.2 The DataTransferItem interface

DataTransferItem

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

DataTransferItemオブジェクトはDataTransferオブジェクトに関連付けられる。

[Exposed=Window]
interface DataTransferItem {
  readonly attribute DOMString kind;
  readonly attribute DOMString type;
  undefined getAsString(FunctionStringCallback? _callback);
  File? getAsFile();
};

callback FunctionStringCallback = undefined (DOMString data);
item.kind

DataTransferItem/kind

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

ドラッグデータ項目の種類、"string"、"file"のいずれかを返す。

item.type

DataTransferItem/type

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

ドラッグデータ項目型文字列を返す。

item.getAsString(callback)

DataTransferItem/getAsString

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

Invokes the callback with the string data as the argument, if the drag data item kind is text.

file = item.getAsFile()

DataTransferItem/getAsFile

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

ドラッグデータアイテムの種類Fileである場合、Fileオブジェクトを返す。

While the DataTransferItem object's DataTransfer object is associated with a drag data store and that drag data store's drag data store item list still contains the item that the DataTransferItem object represents, the DataTransferItem object's mode is the same as the drag data store mode. When the DataTransferItem object's DataTransfer object is not associated with a drag data store, or if the item that the DataTransferItem object represents has been removed from the relevant drag data store item list, the DataTransferItem object's mode is the disabled mode. The drag data store referenced in this section (which is used only when the DataTransferItem object is not in the disabled mode) is the drag data store with which the DataTransferItem object's DataTransfer object is associated.

The kind attribute must return the empty string if the DataTransferItem object is in the disabled mode; otherwise it must return the string given in the cell from the second column of the following table from the row whose cell in the first column contains the drag data item kind of the item represented by the DataTransferItem object:

KindString
Text"string"
File"file"

The type attribute must return the empty string if the DataTransferItem object is in the disabled mode; otherwise it must return the drag data item type string of the item represented by the DataTransferItem object.

The getAsString(callback) method must run the following steps:

  1. If the callback is null, return.

  2. If the DataTransferItem object is not in the read/write mode or the read-only mode, return. The callback is never invoked.

  3. If the drag data item kind is not text, then return. The callback is never invoked.

  4. Otherwise, queue a task to invoke callback, passing the actual data of the item represented by the DataTransferItem object as the argument.

The getAsFile() method must run the following steps:

  1. If the DataTransferItem object is not in the read/write mode or the read-only mode, then return null.

  2. If the drag data item kind is not File, then return null.

  3. Return a new File object representing the actual data of the item represented by the DataTransferItem object.

6.11.4 The DragEvent interface

DragEvent/DragEvent

Support in all current engines.

Firefox3.5+Safari14+Chrome46+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOSNoChrome AndroidNoWebView Android?Samsung Internet?Opera Android?

DragEvent

Support in all current engines.

Firefox3.5+Safari14+Chrome46+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOSNoChrome AndroidNoWebView Android?Samsung Internet?Opera Android?

ドラッグアンドドロップ処理モデルは、複数のイベントを含む。これらはすべてDragEventインターフェイスを使用する。

[Exposed=Window]
interface DragEvent : MouseEvent {
  constructor(DOMString type, optional DragEventInit eventInitDict = {});

  readonly attribute DataTransfer? dataTransfer;
};

dictionary DragEventInit : MouseEventInit {
  DataTransfer? dataTransfer = null;
};
event.dataTransfer

DragEvent/dataTransfer

Support in all current engines.

Firefox3.5+Safari14+Chrome46+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer🔰 10+
Firefox Android?Safari iOSNoChrome AndroidNoWebView Android?Samsung Internet?Opera Android?

イベントのDataTransferオブジェクトを返す。

他のイベントインターフェイスとの整合性を保つため、DragEventインターフェイスはコンストラクタを持つけれども、特に有用ではない。DataTransferオブジェクトは、ドラッグアンドドロップの間にブラウザーによって調整される処理およびセキュリティーモデルを持つので、特に、スクリプトから有用なDataTransferオブジェクトを作成する方法はない。

The dataTransfer attribute of the DragEvent interface must return the value it was initialized to. It represents the context information for the event.

When a user agent is required to fire a DND event named e at an element, using a particular drag data store, and optionally with a specific related target, the user agent must run the following steps:

  1. Let dataDragStoreWasChanged be false.
  2. If no specific related target was provided, set related target to null.

  3. Let window be the relevant global object of the Document object of the specified target element.

  4. If e is dragstart, then set the drag data store mode to the read/write mode and set dataDragStoreWasChanged to true.

    If e is drop, set the drag data store mode to the read-only mode.

  5. Let dataTransfer be a newly created DataTransfer object associated with the given drag data store.

  6. Set the effectAllowed attribute to the drag data store's drag data store allowed effects state.

  7. Set the dropEffect attribute to "none" if e is dragstart, drag, or dragleave; to the value corresponding to the current drag operation if e is drop or dragend; and to a value based on the effectAllowed attribute's value and the drag-and-drop source, as given by the following table, otherwise (i.e. if e is dragenter or dragover):

    effectAlloweddropEffect
    "none""none"
    "copy""copy"
    "copyLink""copy", or, if appropriate, "link"
    "copyMove""copy", or, if appropriate, "move"
    "all""copy", or, if appropriate, either "link" or "move"
    "link""link"
    "linkMove""link", or, if appropriate, "move"
    "move""move"
    "uninitialized" when what is being dragged is a selection from a text control"move", or, if appropriate, either "copy" or "link"
    "uninitialized" when what is being dragged is a selection"copy", or, if appropriate, either "link" or "move"
    "uninitialized" when what is being dragged is an a element with an href attribute"link", or, if appropriate, either "copy" or "move"
    Any other case"copy", or, if appropriate, either "link" or "move"

    Where the table above provides possibly appropriate alternatives, user agents may instead use the listed alternative values if platform conventions dictate that the user has requested those alternate effects.

    For example, Windows platform conventions are such that dragging while holding the "alt" key indicates a preference for linking the data, rather than moving or copying it. Therefore, on a Windows system, if "link" is an option according to the table above while the "alt" key is depressed, the user agent could select that instead of "copy" or "move".

  8. Let event be the result of creating an event using DragEvent.

  9. Initialize event's type attribute to e, its bubbles attribute to true, its view attribute to window, its relatedTarget attribute to related target, and its dataTransfer attribute to dataTransfer.

  10. If e is not dragleave or dragend, then initialize event's cancelable attribute to true.

  11. Initialize event's mouse and key attributes initialized according to the state of the input devices as they would be for user interaction events.

    If there is no relevant pointing device, then initialize event's screenX, screenY, clientX, clientY, and button attributes to 0.

  12. Dispatch event at the specified target element.

  13. Set the drag data store allowed effects state to the current value of dataTransfer's effectAllowed attribute. (It can only have changed value if e is dragstart.)

  14. If dataDragStoreWasChanged is true, then set the drag data store mode back to the protected mode.

  15. Break the association between dataTransfer and the drag data store.

6.11.5 Processing model

When the user attempts to begin a drag operation, the user agent must run the following steps. User agents must act as if these steps were run even if the drag actually started in another document or application and the user agent was not aware that the drag was occurring until it intersected with a document under the user agent's purview.

  1. Determine what is being dragged, as follows:

    If the drag operation was invoked on a selection, then it is the selection that is being dragged.

    Otherwise, if the drag operation was invoked on a Document, it is the first element, going up the ancestor chain, starting at the node that the user tried to drag, that has the IDL attribute draggable set to true. If there is no such element, then nothing is being dragged; return, the drag-and-drop operation is never started.

    Otherwise, the drag operation was invoked outside the user agent's purview. What is being dragged is defined by the document or application where the drag was started.

    img elements and a elements with an href attribute have their draggable attribute set to true by default.

  2. Create a drag data store. All the DND events fired subsequently by the steps in this section must use this drag data store.

  3. Establish which DOM node is the source node, as follows:

    If it is a selection that is being dragged, then the source node is the Text node that the user started the drag on (typically the Text node that the user originally clicked). If the user did not specify a particular node, for example if the user just told the user agent to begin a drag of "the selection", then the source node is the first Text node containing a part of the selection.

    Otherwise, if it is an element that is being dragged, then the source node is the element that is being dragged.

    Otherwise, the source node is part of another document or application. When this specification requires that an event be dispatched at the source node in this case, the user agent must instead follow the platform-specific conventions relevant to that situation.

    Multiple events are fired on the source node during the course of the drag-and-drop operation.

  4. Determine the list of dragged nodes, as follows:

    If it is a selection that is being dragged, then the list of dragged nodes contains, in tree order, every node that is partially or completely included in the selection (including all their ancestors).

    Otherwise, the list of dragged nodes contains only the source node, if any.

  5. If it is a selection that is being dragged, then add an item to the drag data store item list, with its properties set as follows:

    The drag data item type string
    "text/plain"
    The drag data item kind
    Text
    実際のデータ
    The text of the selection

    Otherwise, if any files are being dragged, then add one item per file to the drag data store item list, with their properties set as follows:

    The drag data item type string
    The MIME type of the file, if known, or "application/octet-stream" otherwise.
    The drag data item kind
    File
    実際のデータ
    The file's contents and name.

    Dragging files can currently only happen from outside a navigable, for example from a file system manager application.

    If the drag initiated outside of the application, the user agent must add items to the drag data store item list as appropriate for the data being dragged, honoring platform conventions where appropriate; however, if the platform conventions do not use MIME types to label dragged data, the user agent must make a best-effort attempt to map the types to MIME types, and, in any case, all the drag data item type strings must be converted to ASCII lowercase.

    User agents may also add one or more items representing the selection or dragged element(s) in other forms, e.g. as HTML.

  6. If the list of dragged nodes is not empty, then extract the microdata from those nodes into a JSON form, and add one item to the drag data store item list, with its properties set as follows:

    The drag data item type string
    application/microdata+json
    The drag data item kind
    Text
    実際のデータ
    The resulting JSON string.
  7. 次のサブ手順を実行する:

    1. Let urls be « ».

    2. For each node in the list of dragged nodes:

      If the node is an a element with an href attribute
      Add to urls the result of encoding-parsing-and-serializing a URL given the element's href content attribute's value, relative to the element's node document.
      If the node is an img element with a src attribute
      Add to urls the result of encoding-parsing-and-serializing a URL given the element's src content attribute's value, relative to the element's node document.
    3. If urls is still empty, then return.

    4. Let url string be the result of concatenating the strings in urls, in the order they were added, separated by a U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF).

    5. Add one item to the drag data store item list, with its properties set as follows:

      The drag data item type string
      text/uri-list
      The drag data item kind
      Text
      実際のデータ
      url string
  8. Update the drag data store default feedback as appropriate for the user agent (if the user is dragging the selection, then the selection would likely be the basis for this feedback; if the user is dragging an element, then that element's rendering would be used; if the drag began outside the user agent, then the platform conventions for determining the drag feedback should be used).

  9. Fire a DND event named dragstart at the source node.

    If the event is canceled, then the drag-and-drop operation should not occur; return.

    Since events with no event listeners registered are, almost by definition, never canceled, drag-and-drop is always available to the user if the author does not specifically prevent it.

  10. Fire a pointer event at the source node named pointercancel, and fire any other follow-up events as required by Pointer Events. [POINTEREVENTS]

  11. Initiate the drag-and-drop operation in a manner consistent with platform conventions, and as described below.

    The drag-and-drop feedback must be generated from the first of the following sources that is available:

    1. The drag data store bitmap, if any. In this case, the drag data store hot spot coordinate should be used as hints for where to put the cursor relative to the resulting image. The values are expressed as distances in CSS pixels from the left side and from the top side of the image respectively. [CSS]
    2. The drag data store default feedback.

From the moment that the user agent is to initiate the drag-and-drop operation, until the end of the drag-and-drop operation, device input events (e.g. mouse and keyboard events) must be suppressed.

During the drag operation, the element directly indicated by the user as the drop target is called the immediate user selection. (Only elements can be selected by the user; other nodes must not be made available as drop targets.) However, the immediate user selection is not necessarily the current target element, which is the element currently selected for the drop part of the drag-and-drop operation.

The immediate user selection changes as the user selects different elements (either by pointing at them with a pointing device, or by selecting them in some other way). The current target element changes when the immediate user selection changes, based on the results of event listeners in the document, as described below.

Both the current target element and the immediate user selection can be null, which means no target element is selected. They can also both be elements in other (DOM-based) documents, or other (non-web) programs altogether. (For example, a user could drag text to a word-processor.) The current target element is initially null.

In addition, there is also a current drag operation, which can take on the values "none", "copy", "link", and "move". Initially, it has the value "none". It is updated by the user agent as described in the steps below.

User agents must, as soon as the drag operation is initiated and every 350ms (±200ms) thereafter for as long as the drag operation is ongoing, queue a task to perform the following steps in sequence:

  1. If the user agent is still performing the previous iteration of the sequence (if any) when the next iteration becomes due, return for this iteration (effectively "skipping missed frames" of the drag-and-drop operation).

  2. Fire a DND event named drag at the source node. If this event is canceled, the user agent must set the current drag operation to "none" (no drag operation).

  3. If the drag event was not canceled and the user has not ended the drag-and-drop operation, check the state of the drag-and-drop operation, as follows:

    1. If the user is indicating a different immediate user selection than during the last iteration (or if this is the first iteration), and if this immediate user selection is not the same as the current target element, then update the current target element as follows:

      If the new immediate user selection is null

      Set the current target element to null also.

      If the new immediate user selection is in a non-DOM document or application

      Set the current target element to the immediate user selection.

      そうでなければ

      Fire a DND event named dragenter at the immediate user selection.

      If the event is canceled, then set the current target element to the immediate user selection.

      Otherwise, run the appropriate step from the following list:

      If the immediate user selection is a text control (e.g., textarea, or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data item kind text

      Set the current target element to the immediate user selection anyway.

      If the immediate user selection is the body element

      Leave the current target element unchanged.

      そうでなければ

      Fire a DND event named dragenter at the body element, if there is one, or at the Document object, if not. Then, set the current target element to the body element, regardless of whether that event was canceled or not.

    2. If the previous step caused the current target element to change, and if the previous target element was not null or a part of a non-DOM document, then fire a DND event named dragleave at the previous target element, with the new current target element as the specific related target.

    3. If the current target element is a DOM element, then fire a DND event named dragover at this current target element.

      If the dragover event is not canceled, run the appropriate step from the following list:

      If the current target element is a text control (e.g., textarea, or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data item kind text

      Set the current drag operation to either "copy" or "move", as appropriate given the platform conventions.

      そうでなければ

      Reset the current drag operation to "none".

      Otherwise (if the dragover event is canceled), set the current drag operation based on the values of the effectAllowed and dropEffect attributes of the DragEvent object's dataTransfer object as they stood after the event dispatch finished, as per the following table:

      effectAlloweddropEffectDrag operation
      "uninitialized", "copy", "copyLink", "copyMove", or "all""copy""copy"
      "uninitialized", "link", "copyLink", "linkMove", or "all""link""link"
      "uninitialized", "move", "copyMove", "linkMove", or "all""move""move"
      Any other case"none"
    4. Otherwise, if the current target element is not a DOM element, use platform-specific mechanisms to determine what drag operation is being performed (none, copy, link, or move), and set the current drag operation accordingly.

    5. Update the drag feedback (e.g. the mouse cursor) to match the current drag operation, as follows:

      Drag operationFeedback
      "copy"Data will be copied if dropped here.
      "link"Data will be linked if dropped here.
      "move"Data will be moved if dropped here.
      "none"No operation allowed, dropping here will cancel the drag-and-drop operation.
  4. Otherwise, if the user ended the drag-and-drop operation (e.g. by releasing the mouse button in a mouse-driven drag-and-drop interface), or if the drag event was canceled, then this will be the last iteration. Run the following steps, then stop the drag-and-drop operation:

    1. If the current drag operation is "none" (no drag operation), or, if the user ended the drag-and-drop operation by canceling it (e.g. by hitting the Escape key), or if the current target element is null, then the drag operation failed. Run these substeps:

      1. Let dropped be false.

      2. If the current target element is a DOM element, fire a DND event named dragleave at it; otherwise, if it is not null, use platform-specific conventions for drag cancelation.

      3. Set the current drag operation to "none".

      Otherwise, the drag operation might be a success; run these substeps:

      1. Let dropped be true.

      2. If the current target element is a DOM element, fire a DND event named drop at it; otherwise, use platform-specific conventions for indicating a drop.

      3. If the event is canceled, set the current drag operation to the value of the dropEffect attribute of the DragEvent object's dataTransfer object as it stood after the event dispatch finished.

        Otherwise, the event is not canceled; perform the event's default action, which depends on the exact target as follows:

        If the current target element is a text control (e.g., textarea, or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data item kind text

        Insert the actual data of the first item in the drag data store item list to have a drag data item type string of "text/plain" and a drag data item kind that is text into the text control or editing host or editable element in a manner consistent with platform-specific conventions (e.g. inserting it at the current mouse cursor position, or inserting it at the end of the field).

        そうでなければ

        Reset the current drag operation to "none".

    2. Fire a DND event named dragend at the source node.

    3. Run the appropriate steps from the following list as the default action of the dragend event:

      If dropped is true, the current target element is a text control (see below), the current drag operation is "move", and the source of the drag-and-drop operation is a selection in the DOM that is entirely contained within an editing host

      Delete the selection.

      If dropped is true, the current target element is a text control (see below), the current drag operation is "move", and the source of the drag-and-drop operation is a selection in a text control

      The user agent should delete the dragged selection from the relevant text control.

      If dropped is false or if the current drag operation is "none"

      The drag was canceled. If the platform conventions dictate that this be represented to the user (e.g. by animating the dragged selection going back to the source of the drag-and-drop operation), then do so.

      そうでなければ

      The event has no default action.

      For the purposes of this step, a text control is a textarea element or an input element whose type attribute is in one of the Text, Search, Tel, URL, Email, Password, or Number states.

User agents are encouraged to consider how to react to drags near the edge of scrollable regions. For example, if a user drags a link to the bottom of the viewport on a long page, it might make sense to scroll the page so that the user can drop the link lower on the page.

This model is independent of which Document object the nodes involved are from; the events are fired as described above and the rest of the processing model runs as described above, irrespective of how many documents are involved in the operation.

6.11.6 Events summary

この節は非規範的である。

次のイベントは、ドラッグアンドドロップモデルに関与する。

イベント名ターゲット取消可能か?Drag data store modedropEffectデフォルトの動作
dragstart

HTMLElement/dragstart_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
Source node✓取消可能Read/write mode"none"ドラッグアンドドロップ操作を開始する
drag

HTMLElement/drag_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
Source node✓取消可能Protected mode"none"ドラッグアンドドロップ操作を続行する
dragenter

HTMLElement/dragenter_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
即時ユーザー選択またはbody要素✓取消可能Protected modeBased on effectAllowed value潜在的なターゲット要素として即時ユーザー選択を拒絶する
dragleave

HTMLElement/dragleave_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
Previous target elementProtected mode"none"なし
dragover

HTMLElement/dragover_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
Current target element✓取消可能Protected modeBased on effectAllowed value"none"に現在のドラッグ操作リセットする
drop

HTMLElement/drop_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
Current target element✓取消可能Read-only modeCurrent drag operation変化する
dragend

HTMLElement/dragend_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
Source nodeProtected modeCurrent drag operation変化する

All of these events bubble, are composed, and the effectAllowed attribute always has the value it had after the dragstart event, defaulting to "uninitialized" in the dragstart event.

6.11.7 The draggable attribute

Global_attributes/draggable

Support in all current engines.

Firefox2+Safari5+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

すべてのHTML要素draggableコンテンツ属性設定を持ってもよい。The draggable attribute is an enumerated attribute with the following keywords and states:

キーワード状態概要
truetrueThe element will be draggable.
falsefalseThe element will not be draggable.

The attribute's missing value default and invalid value default are both the auto state. The auto state uses the default behavior of the user agent.

draggable属性を持つ要素はまた、非視覚的な相互作用の目的のために要素を名付けるtitle属性を持つべきである。

element.draggable [ = value ]

要素がドラッグ可能である場合にtrueを返す。そうでなければfalseを返す。

デフォルトを上書きしdraggableコンテンツの属性を設定するための、設定が可能である。

The draggable IDL attribute, whose value depends on the content attribute's in the way described below, controls whether or not the element is draggable. Generally, only text selections are draggable, but elements whose draggable IDL attribute is true become draggable as well.

If an element's draggable content attribute has the state true, the draggable IDL attribute must return true.

Otherwise, if the element's draggable content attribute has the state false, the draggable IDL attribute must return false.

Otherwise, the element's draggable content attribute has the state auto. If the element is an img element, an object element that represents an image, or an a element with an href content attribute, the draggable IDL attribute must return true; otherwise, the draggable IDL attribute must return false.

If the draggable IDL attribute is set to the value false, the draggable content attribute must be set to the literal value "false". If the draggable IDL attribute is set to the value true, the draggable content attribute must be set to the literal value "true".

6.11.8 Security risks in the drag-and-drop model

User agents must not make the data added to the DataTransfer object during the dragstart event available to scripts until the drop event, because otherwise, if a user were to drag sensitive information from one document to a second document, crossing a hostile third document in the process, the hostile document could intercept the data.

For the same reason, user agents must consider a drop to be successful only if the user specifically ended the drag operation — if any scripts end the drag operation, it must be considered unsuccessful (canceled) and the drop event must not be fired.

User agents should take care to not start drag-and-drop operations in response to script actions. For example, in a mouse-and-window environment, if a script moves a window while the user has their mouse button depressed, the UA would not consider that to start a drag. This is important because otherwise UAs could cause data to be dragged from sensitive sources and dropped into hostile documents without the user's consent.

User agents should filter potentially active (scripted) content (e.g. HTML) when it is dragged and when it is dropped, using a safelist of known-safe features. Similarly, relative URLs should be turned into absolute URLs to avoid references changing in unexpected ways. This specification does not specify how this is performed.

Consider a hostile page providing some content and getting the user to select and drag and drop (or indeed, copy and paste) that content to a victim page's contenteditable region. If the browser does not ensure that only safe content is dragged, potentially unsafe content such as scripts and event handlers in the selection, once dropped (or pasted) into the victim site, get the privileges of the victim site. This would thus enable a cross-site scripting attack.