How does JavaScript prevent events from bubbling and browser default behavior
This article mainly introduces JavaScript how to prevent event bubbling and browser default behavior related knowledge, the content is detailed and easy to understand, easy to operate, has a certain reference value, I believe you will learn something after reading this JavaScript article on how to prevent event bubbling and browser default behavior, let's take a look at it.
1. Prevent event bubbling compatible with W3C browsers
Function cBubble (e) {
If (e.stopPropagation) {
E.stopPropagation (); / / ie9+
} else {/ / ie678
E.cancelBubble = true
}
}
two。 Block browser default behavior
Function cDefault (e) {
If (e.preventDefault) {/ / ie9+
E.preventDefault ()
} else {/ / ie 678
E.returnValue = false
}
}
3. Block default details
The method of W3C is e.preventDefault ()
IE uses e.returnValue = false
PreventDefault it is a method of the event object (Event)
The function is to cancel the default behavior of a target element.
Since we are talking about the default behavior, of course, the element must have the default behavior before it can be canceled.
If the element itself has no default behavior, the call is of course invalid.
What element has default behavior?
Such as links
Submit button, etc.
When the cancelable of the Event object is false, there is no default behavior
Even if there is a default behavior, calling preventDefault will not work.
This is the end of the article on "how to prevent JavaScript from bubbling events and browser default behavior". Thank you for reading! I believe you all have a certain understanding of "how to prevent events from bubbling and browser default behavior". If you want to learn more, you are welcome to follow the industry information channel.