Cancel click event in the mouseup event handler

前端 未结 14 2437
梦毁少年i
梦毁少年i 2020-12-09 14:53

Writing some drag&drop code, I\'d like to cancel the click events in my mouseup handler. I figured preventing default should do the trick, but the click event is still f

14条回答
  •  借酒劲吻你
    2020-12-09 15:20

    i recently faced with the same problem. Here's my solution :)

        initDrag: function (element) {
            var moved = false,
                target = null;
    
            function move(e) {
                // your move code
                moved = true;
            };
    
            function end(e) {
                var e = e || window.event,
                    current_target = e.target || e.srcElement;
    
                document.onmousemove = null;
                document.onmouseup = null;
    
                // click happens only if mousedown and mouseup has same target
                if (moved && target === current_target) 
                    element.onclick = click;
    
                moved = false;
            };
    
            function click(e) {
                var e = e || window.event;
    
                e.preventDefault();
                e.stopPropagation();
    
                // this event should work only once
                element.onclick = null;
            };
    
            function init(e) {
                var e = e || window.event;
                target = e.target || e.srcElement;
    
                e.preventDefault();
    
                document.onmousemove = move;
                document.onmouseup = end;
            };
    
            element.onmousedown = init;
        };
    

提交回复
热议问题