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

后端 未结 5 1253
南笙
南笙 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:40

    If you've got a lot of clickable elements like I have, you're gonna want to create a global mouse catcher and set your mouseup code within the mousedowns of clicked element. Here's the code I used.

        var MouseCatcher=function()
        {
            this.init=function()
            {
                var mc = this; 
                $(document).bind({
                    mouseup:function(e) 
                    {
                        mc.mouseup();
                    }
                });
            }
            this.mouseup=function()
            {
                return false;
            }
        }
        var mouseCatcher = new MouseCatcher();
        mouseCatcher.init();
    
    
    
        $('#clickableElement').bind({
            mousedown: function(e)
            {
                console.log('mousedown on element');
    
                mouseCatcher.mouseup=function()
                {
                    console.log('mouseup called from MouseCatcher');
                    this.mouseup = function(){return false;}
                }
    
            },
            mouseup:function(e)
            {
                //mouseup within element, no use here.
            }
        });
    

提交回复
热议问题