What's the difference between event.stopPropagation and event.preventDefault?

后端 未结 7 1287
余生分开走
余生分开走 2020-11-22 00:52

They seem to be doing the same thing...
Is one modern and one old? Or are they supported by different browsers?

When I handle events myself (without framework) I

7条回答
  •  渐次进展
    2020-11-22 01:26

    This is the quote from here

    Event.preventDefault

    The preventDefault method prevents an event from carrying out its default functionality. For example, you would use preventDefault on an A element to stop clicking that element from leaving the current page:

    //clicking the link will *not* allow the user to leave the page 
    myChildElement.onclick = function(e) { 
        e.preventDefault(); 
        console.log('brick me!'); 
    };
    
    //clicking the parent node will run the following console statement because event propagation occurs
    logo.parentNode.onclick = function(e) { 
        console.log('you bricked my child!'); 
    };
    

    While the element's default functionality is bricked, the event continues to bubble up the DOM.

    Event.stopPropagation

    The second method, stopPropagation, allows the event's default functionality to happen but prevents the event from propagating:

    //clicking the element will allow the default action to occur but propagation will be stopped...
    myChildElement.onclick = function(e) { 
        e.stopPropagation();
        console.log('prop stop! no bubbles!'); 
    };
    
    //since propagation was stopped by the child element's onClick, this message will never be seen!
    myChildElement.parentNode.onclick = function(e) { 
        console.log('you will never see this message!'); 
    };
    

    stopPropagation effectively stops parent elements from knowing about a given event on its child.

    While a simple stop method allows us to quickly handle events, it's important to think about what exactly you want to happen with bubbling. I'd bet that all a developer really wants is preventDefault 90% of the time! Incorrectly "stopping" an event could cause you numerous troubles down the line; your plugins may not work and your third party plugins could be bricked. Or worse yet -- your code breaks other functionality on a site.

提交回复
热议问题