点击页面其他部分关闭当前下拉框
步骤
-
监听admin模块的点击事件,并设置每次点击时检查当前下拉框部分是否展示,是则改为隐藏,否则改为展示。
-
dropDown.style.display == "none"
时设置dropDown.style.display = "block";
-
dropDown.style.display == "block"
时设置dropDown.style.display = "none";
-
-
阻止该点击事件冒泡
userBox.onclick = function (e) {e.stopPropagation();}
事件冒泡会导致点击userBox模块,先触发userBox的点击事件,又触发它父组件的点击事件。
当不阻止事件冒泡时
-
设置全局的点击事件监听函数,监听到点击即关闭下拉框
dropDown.style.display = "none";
完整代码
<!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>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
.tab-list {
background-color: #001529;
}
.userBox {
display: inline-block;
height: 40px;
width: 80px;
line-height: 40px;
margin-left: 100px;
text-align: center;
color: #fff;
cursor: pointer;
}
.userBox span {
padding: 0 8px;
}
.user-dropdown-box {
display: none;
position: relative;
font-size: 12px;
z-index: 1;
}
.dropdown-list {
position: absolute;
top: 0px;
left: 100px;
width: 140px;
background-color: #3b3d4c;
color: #fff;
text-align: left;
}
.dropdown-item {
width: 120px;
height: 40px;
line-height: 40px;
padding-left: 20px;
cursor: pointer;
}
.dropdown-item:hover {
background-color: #43475e;
}
</style>
</head>
<body>
<div class="tab-list">
<div class="userBox">
<span>admin</span>
</div>
</div>
<div class="user-dropdown-box">
<ul class="dropdown-list">
<li><p class="dropdown-item" onclick="loginOut()">登出</p></li>
<li>
<p class="dropdown-item" onclick="updatePassword()">修改密码</p>
</li>
</ul>
</div>
</body>
<script>
// 点击admin用户区域,展示或隐藏下拉框
function showDropdown() {
const dropDown = document.querySelector(".user-dropdown-box");
const userBox = document.querySelector(".userBox");
const userBoxSpan = document.querySelector(".userBox span");
//当鼠标点击userBox时处理下拉列表的展开/收起
userBox.onclick = function (e) {
if (dropDown.style.display == "none" || dropDown.style.display == "") {
// 展开
userBox.style.background = "#3b3d4c";
dropDown.style.display = "block";
} else {
//收起
userBox.style.background = "#001529";
dropDown.style.display = "none";
}
// 阻止事件冒泡,防止外部监听点击事件的函数被userBox.click影响
e.stopPropagation();
};
}
// 点击页面其他部分,关闭当前下拉框
function initCloseFunction() {
const userBox = document.querySelector(".userBox");
const dropDown = document.querySelector(".user-dropdown-box");
// 监听全局的点击事件,触发就关闭下拉框
window.addEventListener("click", () => {
userBox.style.background = "#001529";
dropDown.style.display = "none";
});
}
showDropdown();
initCloseFunction();
</script>
</html>