简体   繁体   English

ondragenter提醒容器的.id

[英]ondragenter alert the container's .id

I've an img that I just wanna drop in the div called #div1 . 我有一张img,我只想放入#div1的div中。 When I drag over the div I would like to get the container's id, but this is making lots of alerts, no just one.... 当我将鼠标悬停在div上时,我想获取容器的ID,但这会发出很多警报,而不仅仅是一个。

 <img id="drag1" 
      src="http://www.vectortemplates.com/raster/batman-logo-big.gif" 
      draggable="true" 
      ondragstart="drag(event, this)" 
      width="336" 
      height="69"/>

  <div id="div1"
       ondrop="drop(event)"  
       ondragenter="allowDrop(event, this)">
  </div>

JS : JS:

function allowDrop(ev, obj)
{
    alert(obj.id);
}

So Why I'm recibing lots of Alerts??? 那么,为什么我要接收很多警报???

See the Demo there : http://jsfiddle.net/PbjJv/ 观看演示: http//jsfiddle.net/PbjJv/

Explanation 说明

The ondragover event is fired every pixel your cursor moved on the div . 您的光标在div上移动的每个像素都会触发 ondragover事件。 Try to use ondragleave event which is fired when you release the mouse button. 尝试使用ondragleave事件,当您释放鼠标按钮时会触发该事件。


Solution

Use the ondragleave event on your div : 在div上使用ondragleave事件:

HTML HTML

 <div id="div1"  ondragleave="allowDrop(event, this)"></div>

JSFiddle 的jsfiddle

This accepted answer is incorrect. 这个已接受的答案是错误的。

From the MDN: 从MDN:

The drop event is fired when an element or text selection is dropped on a valid drop target. 当将元素或文本选择放置在有效放置目标上时,将触发放置事件。

And: 和:

The dragleave event is fired when a dragged element or text selection leaves a valid drop target. 当拖动的元素或文本选择离开有效的放置目标时,将触发dragleave事件。

Calling allowDrop() when the ondragleave event fires would allow dropping to the DIV after the drag has left that element. ondragleave事件触发时调用allowDrop()将允许在拖动离开该元素后放到DIV。 The element in question would not receive the final ondrop event when the user relase the mouse button. 当用户释放鼠标按钮时,所讨论的元素将不会收到最终的ondrop事件。

The question seem to have been edited, it seems fine to me at this point. 这个问题似乎已经被编辑,对我而言这似乎很好。 The jsfiddle referenced in the OPs question suggests this as it use ondragover instead of ondragenter on div1 . OP问题中引用的jsfiddle提出了这一建议,因为它在div1上使用ondragover而不是ondragenter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM