js之阻止事件冒泡(待修改)和阻止默认事件

时间:2024-01-19 23:53:08

阻止默认事件(event.stopPropagation()):

<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,user-scalable=no" /><title></title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/css/css.css" rel="stylesheet" type="text/css" />
<script>
window.onload=function(){
var oA=document.getElementsByTagName("a")[0];
oA.onclick=function(event){
event.preventDefault();
console.log("阻止了默认事件");
};
}
</script>
</head>
<body>
<a>aaa</a>
</body>
</html>

阻止事件冒泡(event.stopPropagation()):

<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<script src="jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(event){
$("#z_body").slideDown(1000);
event.stopPropagation();
});
$("#z_body").click(function(event){
event.stopPropagation();
});
$(document).click(function(){
$("#z_body").slideUp();
})
});
</script>
<style>
*{margin:0px;padding:0px;}
body{max-320px;margin:0 auto;width:320px;}
#z_body{width:320px;height:auto;line-height:40px;background:#ccc;color:#000000;display:none;max-width:320px;margin-top:30px;}
#z_body ul{}
#z_body ul li{width:266px;;height:39px;line-height:39px;background:#40205d;border-top:1px solid #666666;border-bottom:1px solid #666666;list-style:none;font-size:16px;color:#fff;padding-left:54px;}
#btn{height:30px;display:block;text-align:center;font-weight:600;background:pink;width:320px;line-height:30px;position:fixed;top:0px;}
</style>
</head>
<body>
<a id="btn">菜单</a>
<div id="z_body">
<ul>
<li>网站首页</li>
<li>整形中心</li>
<li>皮肤中心</li>
<li>网站首页</li>
<li>整形中心</li>
<li>皮肤中心</li>
<li>网站首页</li>
</ul>
</div>
</body>
</html>