When the <a> tag has an href attribute, it will automatically navigate to the linked page or scroll to the anchor. By preventing the default behavior of the <a> tag, clicking on the link will not navigate.
<ahref="https://blog.touchczy.top"id="t1">Click to navigate</a><scripttype="text/javascript"> document.getElementById("t1").addEventListener("click",(e)=>{ e.preventDefault();})</script>
Right-clicking on a browser page will display a menu. By preventing the default behavior of the document, the menu will not appear when right-clicking on the page. Alternatively, a custom context menu can be created by listening to and preventing the default behavior.
When an <input> or <textarea> element is focused, typing on the keyboard will automatically input characters. By preventing the default behavior, typing on the keyboard will not input characters. This event can be used to filter input data, for example, allowing only numeric input.
If there is an <input> or <button> with type set to submit in a form, it will trigger the form submission. By preventing the default behavior, the form will not be automatically submitted.
The recommended way to prevent default behaviors by the W3C is to use event.preventDefault(). This method only prevents the default behavior without stopping the event propagation.
For browsers like IE8 and earlier, preventing default behaviors requires using window.event.returnValue = false.
In the event handler function, directly returning false can also prevent the default behavior, but this only works in the DOM Level 0 event model. Additionally, in jQuery, using return false will both prevent the default behavior and stop event propagation.
<!DOCTYPEhtml><html><head><title>Default Behaviors and Prevention</title></head><body><ahref="https://blog.touchczy.top"id="t1">Click to jump to the link</a><inputid="t3"/><inputid="t4"type="checkbox"/><formaction="/"id="t5"><inputtype="submit"name="btn"/></form><ahref="https://blog.touchczy.top"id="t6">Click to jump to the link</a></body><scripttype="text/javascript"> document.getElementById("t1").addEventListener("click",(e)=>{ e.preventDefault();}) document.addEventListener("contextmenu",(e)=>{ e.preventDefault();}) document.getElementById("t3").addEventListener("keydown",(e)=>{ e.preventDefault();}) document.getElementById("t4").addEventListener("click",(e)=>{ e.preventDefault();}) document.getElementById("t5").addEventListener("click",(e)=>{ e.preventDefault();}) document.getElementById("t6").onclick=(e)=>{returnfalse;}</script></html>