admin管理员组

文章数量:1310542

From MDN Documentation I can read:

Drag - Fired when an element or text selection is being dragged. Dragstart - Fired when the user starts dragging an element or text selection


But ... why my function was ignored by browser when I attach it to "drag" event and was perfectly ok when I gave it "dragstart" instead? From the definition I assume that them both do the same (?)

function itemDrag(e) {
e.dataTransfer.setData("text", e.target.id);  
}


document.getElementById("try1").addEventListener("dragstart",function(){
    itemDrag(event);
});

From MDN Documentation I can read:

Drag - Fired when an element or text selection is being dragged. Dragstart - Fired when the user starts dragging an element or text selection

https://developer.mozilla/en-US/docs/Web/API/HTML_Drag_and_Drop_API

But ... why my function was ignored by browser when I attach it to "drag" event and was perfectly ok when I gave it "dragstart" instead? From the definition I assume that them both do the same (?)

function itemDrag(e) {
e.dataTransfer.setData("text", e.target.id);  
}


document.getElementById("try1").addEventListener("dragstart",function(){
    itemDrag(event);
});
Share Improve this question asked Mar 24, 2017 at 14:26 ZebraZebra 1894 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

The dragstart event is fired when the user starts dragging an element or text selection.

The drag event is fired when an element or text selection is being dragged (every few hundred milliseconds).

So dragstart should be fired once, drag should be fired continuously.

This es from the MDN pages.


https://developer.mozilla/en-US/docs/Web/Events/drag

https://developer.mozilla/en-US/docs/Web/Events/dragstart


example:

let continu = 0;

document.addEventListener("dragstart", function( event ) {

     console.log('start');
     
}, false);
  
document.addEventListener("drag", function( event ) {

  if(continu < 5){
     console.log('continu');
  }
  
  continu ++;
  
}, false);
<div class="dropzone">
  <div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)">
    This div is draggable
  </div>
</div>
<div class="dropzone"></div>
<div class="dropzone"></div>
<div class="dropzone"></div>


Drag related events:

  • drag
  • dragstart
  • dragend
  • dragover
  • dragenter
  • dragleave
  • dragexit
  • drop

本文标签: javascriptExact difference between drag and dragstart event type ()Stack Overflow