JS——取消事件冒泡,实现div的显示与隐藏 event.cancelBubble = true;

时间:2021-08-01 21:38:32
<!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>
<style>
#div1 { width:300px; height:450px; background-color:#99FFFF; display:none;}
</style> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script>
window.onload = function(){
var myBtn1 = document.getElementById("btn1");
var myDiv1 = document.getElementById("div1"); myDiv1.onclick = function(ev){
var divEvent = ev || event;//事件支持火狐浏览器和IE浏览器
divEvent.cancelBubble = true;//取消事件冒泡
};
//点击按钮时,div显示,在函数中加入参数ev
myBtn1.onclick = function(ev){
var myEvent = ev || event;//事件支持火狐浏览器和IE浏览器
myDiv1.style.display = "block";
myEvent.cancelBubble = true;//取消事件冒泡 };
//点击其他的空白页面是,div1消失
document.onclick = function(){
myDiv1.style.display = "none";
};
};
</script> </head> <body>
<input id="btn1" type="button" value="显示" />
<div id="div1">点击按钮,我显示了。点击空白处试试</div>
</body>
</html>