Stop propagation for all events

前端 未结 4 1473
野性不改
野性不改 2021-01-08 00:38

I am calling e.stopPropagation() on almost every event that I have for my current application. Is there any way to just stop the propagation for every event wit

相关标签:
4条回答
  • 2021-01-08 00:54

    Try this. It requires jQuery.

    $('*').on('click', function(e){
       e.stopPropagation();
    });
    
    0 讨论(0)
  • 2021-01-08 00:57

    You could bind all events (remove the ones you don't need):

    $('*').bind('blur change click dblclick error focus focusin focusout hover keydown keypress keyup load mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup resize scroll select submit', function(event){
        event.stopPropagation();
    });
    

    Take a look at possible events at jQuery Docs

    0 讨论(0)
  • 2021-01-08 01:03

    No it cannot be declared Globally

    The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.

    For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

    http://api.jquery.com/event.stopPropagation/

    0 讨论(0)
  • 2021-01-08 01:14

    To build on Alex's response, in vanilla JS and with a few more events (all the keyboard and click events I could find):

    /**
     * Disable all user events on the page
     *
     * @returns {function()} a function to cancel the disabling
     */
    const disableAllUserEvents = () => {
        const events = ["click", "contextmenu", "dblclick", "mousedown", "mouseenter", "mouseleave", "mousemove",
            "mouseover", "mouseout", "mouseup", "keydown", "keypress", "keyup", "blur", "change", "focus", "focusin",
            "focusout", "input", "invalid", "reset", "search", "select", "submit", "drag", "dragend", "dragenter",
            "dragleave", "dragover", "dragstart", "drop", "copy", "cut", "paste", "mousewheel", "wheel", "touchcancel",
            "touchend", "touchmove", "touchstart"];
    
        const handler = event => {
            event.stopPropagation();
            event.preventDefault();
    
            return false;
        };
    
        for (let i = 0, l = events.length; i < l; i++) {
            document.addEventListener(events[i], handler, true);
        }
    
        return () => {
            for (let i = 0, l = events.length; i < l; i++) {
                document.removeEventListener(events[i], handler, true);
            }
        };
    };
    

    Edit: Just know that this isn't a secure solution, as those events can be retrieved and canceled: Use Chrome's webkit inspector to remove an event listener

    0 讨论(0)
提交回复
热议问题