Drag drop with handle

China☆狼群 提交于 2021-02-17 21:23:34

问题


I have a div which contains a span that is 16x16px. I want the drag event to start when user clicks and drags this icon but it should drag the whole div. I'm trying to follow this tutorial here: http://www.html5rocks.com/en/tutorials/dnd/basics/

I cant figureout how to do this with a handle. Please adivise.


回答1:


I have slightly modified SaphuA's answer to allow highlighting text.

The trick is not to add the draggable attribute until the drag handle gets the mousedown event.

Here's a demo: https://jsfiddle.net/a6tgy9so/1/




回答2:


Here's a working example: https://jsfiddle.net/pwt1cbjc/

var draggable = document.getElementById('draggable');
var handle = document.getElementById('handle');
var target = false;
draggable.onmousedown = function(e) {
    target = e.target;
};
draggable.ondragstart = function(e) {
    if (handle.contains(target)) {
        e.dataTransfer.setData('text/plain', 'handle');
    } else {
        e.preventDefault();
    }
};
#draggable {
    width: 100px;
    height: 100px;
    border: 1px solid black;
}
#handle {
    width: 0;
    height: 0;
    border-right: 20px solid transparent;
    border-top: 20px solid black;
    cursor: move;
}
<h1>Drag Handle</h1>

<div id="draggable" draggable="true">
    <div id="handle">
    </div>
</div>


来源:https://stackoverflow.com/questions/26283661/drag-drop-with-handle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!