javascript prevents event bubbling and browser default behavior

  • 2021-07-13 03:56:25
  • OfStack

1. Prevent event bubbling and make it a capture event trigger mechanism.


function stopBubble(e) { 
// If an event object is provided, this is 1 A mistake IE Browser  
if ( e && e.stopPropagation ) 
  // So it supports W3C Adj. stopPropagation() Method  
  e.stopPropagation(); 
else
  // Otherwise, we need to use the IE The way to cancel the event bubbling  
  window.event.cancelBubble = true; 
}

2. When the key is pressed and you do not want the key to continue to be passed to a text box object such as HTML, you can cancel the return value. That is, stop the default event default behavior.


 // Block the default behavior of browsers  
function stopDefault( e ) { 
  // Block default browser actions (W3C) 
  if ( e && e.preventDefault ) 
    e.preventDefault(); 
  //IE The way to prevent the default action of functionalists in  
  else
    window.event.returnValue = false; 
  return false; 
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title> Effect test </title>
<script language="javascript" type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$('div.c1').click(function(e){alert(' Clicked div');});
$('div.c2').click(function(e){alert(' Clicked div');stopBubble(e);});
$(document).click(function(e){alert(' Clicked document');});
$('#txt1').val('123');
$('#txt1').click(function(e){stopBubble(e);});
$('#txt1').keydown(function(e){stopDefault(e);alert(' You pressed the key value '+e.keyCode); });
})
function stopBubble(e) { 
// If an event object is provided, this is 1 A mistake IE Browser  
  if ( e && e.stopPropagation ) 
  // So it supports W3C Adj. stopPropagation() Method  
  e.stopPropagation(); 
   else 
  // Otherwise, we need to use the IE The way to cancel the event bubbling  
  window.event.cancelBubble = true; 
} 
// Block the default behavior of browsers  
function stopDefault( e ) { 
  // Block default browser actions (W3C) 
  if ( e && e.preventDefault ) 
    e.preventDefault(); 
  //IE The way to prevent the default action of functionalists in  
  else 
    window.event.returnValue = false; 
  return false; 
}
</script>
<style type="text/css">
body{
font-size:14px;
  }
}
.c1{
  font-family:"Arial Unicode MS"
  }
.c2{
  font-family:helvetica,simsun,arial,clean
  }
</style>
</head>
<body>
<div class="c1"> Text for testing , Here is the style C1, Click to trigger an event as a bubble .</div><hr/>
<div class="c2"> Text for testing , Here is the style C2, Click to trigger an event as a capture .</div><hr/>
<div><input id="txt1" name="Text1" type="text" /></div><hr/>
</body>
</html>

Related articles: