Drag drop with handle

后端 未结 2 1732
傲寒
傲寒 2021-02-07 11:28

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 t

2条回答
  •  广开言路
    2021-02-07 11:45

    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;
    }

    Drag Handle

提交回复
热议问题