<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
button{
width:300px;
height:40px;
}
div{
width:300px;
height:500px;
background-color:red;
display:none;
}
</style>
</head>
<body>
<!-- 要求:做一个下拉菜单,在点击时,让该菜单展示出来,点击页面的其他位置时,菜单隐藏 -->
<button>下拉框</button>
<div></div>
<script>
var oBtn=document.querySelector("button");
var oDiv=document.querySelector("div");
var b=true; //布尔值开关(一个按钮执行不同效果的时候使用)
oBtn.onclick=function(){
// 最初是true,所以一点击就显示,后来b变为false再点击就不显示,这样循环
oDiv.style.display=b ? "block" : "none";
b=!b; //b是全局的,所以b改变影响的是全局b
event.cancelBubble=true; //不取消冒泡,下拉框无法出来
}
document.onclick=function(){
oDiv.style.display="none";
b=true; //不写这个的话会出问题
}
</script>
</body>
</html>
练习-下拉框(冒泡问题)
最新推荐文章于 2021-11-05 20:18:41 发布