js点击显示,点击其他地方关闭
话不多说直接上代码
<!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>
body {
width: 100%;
height: 500px;
}
#outside {
width: 200px;
height: 50px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div id="outside">
点击这里出现列表
</div>
<div id="modal" style="display: none;">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<script>
window.onload = function () {
const outside = document.getElementById("outside");
outside.addEventListener("click", viewModal);
const body = document.getElementsByTagName("body")[0];
body.addEventListener("click", hideModal);
const modal = document.getElementById("modal");
// 防止点击 modal 列表时列表消失
modal.addEventListener("click", (e) => { stopProp(e); });
}
function viewModal (e) {
stopProp(e); // 防止事件冒泡导致触发body上绑定的点击事件
const modal = document.getElementById("modal");
const disp = modal.style.display;
modal.style.display = disp === "none" ? "block" : "none";
}
function hideModal () {
const o = document.getElementById("modal");
o.style.display = "none";
}
/**
* 阻止事件冒泡
*/
function stopProp (e) {
e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
}
</script>
</body>
</html>
文章目录
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。