jQuery detect mousedown inside an element and then mouseup outside the element

后端 未结 5 1245
南笙
南笙 2020-12-30 02:50

I have something similar to a drawing canvas, and I capture it\'s state on mouseup for undo purposes. The canvas isn\'t full screen, so you can draw with a brush and release

5条回答
  •  遥遥无期
    2020-12-30 03:44

    Hopefully you find this little solution to be helpful. You can see it in action here: http://jsfiddle.net/neopreneur/PR2yE/

    $(document).ready(function(){
        var startMouseDownElement = null;
    
        $('#element').mousedown(function(){
            // do whatever
            //...
    
            // set mousedown start element
            startMouseDownElement = $(this);
        });
    
        // handle bad mouseup
        // $('#container, #container *').mouseup would be more efficient in a busy DOM
        $('body *').mouseup(function(event){
            event.stopPropagation(); // stop bubbling
            if($(this).attr('id') != $(startMouseDownElement).attr('id')){
                //oops, bad mouseup
                alert('bad mouseup :(');  
            }
        });
    });
    

提交回复
热议问题