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

后端 未结 5 1227
南笙
南笙 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

    A possible implementation of mike's and waitingforatrain's answers in GWT. In the html head manage mouse up events (javascript code):

       var mouseUpHook = false;
       $(document).mouseup(function() {
           if (mouseUpHook) {
               mouseUpHook(null);
               mouseUpHook = false;
           }
       });
    

    Let your custom Widget class implement MouseDownHandler and MouseUpHandler, and add those lines in your constructor to receive mouse events (java code):

        addDomHandler(this, MouseDownEvent.getType());
        addDomHandler(this, MouseUpEvent.getType());
    

    Finally, add those methods in your custom Widget class (java and javascript code):

    @Override
    public void onMouseUp (MouseUpEvent event) {
        removeMouseUpHook();
    
        // ... do something else
    }
    
    private native void hookMouseUp () /*-{
        $wnd.$('body').addClass('noselect');
        var myThis = this;
        $wnd.mouseUpHook = function () {
            myThis.@your.custom.widget.class.full.qualified.Name::onMouseUp(Lcom/google/gwt/event/dom/client/MouseUpEvent;)(null);
        };
    }-*/;
    
    private native void removeMouseUpHook () /*-{
        $wnd.$('body').removeClass('noselect');
    }-*/;
    
    @Override
    public void onMouseDown (MouseDownEvent event) {
        hookMouseUp();
    
        // ... do something else
    
        event.preventDefault();
    }
    

    Last line is usefull to prevent image dragging. Infact, user-select: none is not sufficent.

提交回复
热议问题