HTML5 - Drag N Drop with divs and inner-images

2019-02-26 00:14发布

问题:

I have this type of element:

<div draggable="true" id="item" style="margin:20px;background:red;height:400px;width:400px;">
    <a href="#" target="_blank">
        <img style="margin:40px;" src="http://www.placekitten.com/100/100" alt="">
    </a>
</div>

I want to be able to:

  1. Drag the whole div, even if I click on the /anchorimage (before dragging).
  2. Still respond normally to an anchor/image click (without a drag).

Right now, only the image is dragged when I click on it.

Here's a fiddle: http://jsfiddle.net/M5tBd/

回答1:

As per the HTML5 Editor's Draft spec, Images and Anchors with a href element are both elements that are, by default draggable. Your anchor is probably capturing the dragstart event, preventing the div from ever getting it. Try setting draggable="false" on your <img> and <a> elements.

<div draggable="true" id="item" style="margin:20px;background:red;height:400px;width:400px;">
<a href="#" target="_blank" draggable="false">
    <img style="margin:40px;" src="http://www.placekitten.com/100/100" alt="" draggable="false">
</a>

Your fiddle doesn't even work dragging the img element for me in Chrome under Ubuntu, so you may have other issues besides this.