<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 150px;
height: 300px;
background-color: red;
display: none;
}
</style>
</head>
<body>
<button>按钮</button>
<div></div>
<script>
var btn = document.querySelector('button');
var div = document.querySelector('div');
btn.onclick = function(ev){
var ev = ev || window.event;
stopPropagation(ev);
div.style.display = 'block';
}
document.onclick = function(){
div.style.display = 'none';
}
//阻止冒泡的兼容
function stopPropagation(ev){
if(ev.stopPropagation){
ev.stopPropagation();//标准浏览器
}else{
ev.cancelBubble = true;//ie8及以下
}
}
</script>
</body>
</html>
从零开始学JavaScript——JS阻止冒泡的兼容及二级菜单
最新推荐文章于 2023-04-01 16:28:42 发布