单击外部自定义快捷菜单将其关闭是一种常见的用户界面交互设计。这种设计允许用户通过点击菜单外部区域来关闭弹出的菜单或对话框,从而提升用户体验。
:focus-within
伪类:利用CSS伪类来控制菜单的显示状态。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Close Menu on Outside Click</title>
<style>
.menu {
display: none;
position: absolute;
top: 50px;
left: 50px;
background: white;
border: 1px solid #ccc;
padding: 10px;
}
.menu.active {
display: block;
}
</style>
</head>
<body>
<button id="menuButton">Open Menu</button>
<div class="menu" id="menu">
<p>This is a custom menu.</p>
</div>
<script>
const menuButton = document.getElementById('menuButton');
const menu = document.getElementById('menu');
let isMenuOpen = false;
menuButton.addEventListener('click', () => {
isMenuOpen = !isMenuOpen;
menu.classList.toggle('active', isMenuOpen);
});
document.addEventListener('click', (event) => {
if (!menu.contains(event.target) && isMenuOpen) {
isMenuOpen = false;
menu.classList.remove('active');
}
});
// Prevent clicks inside the menu from closing it
menu.addEventListener('click', (event) => {
event.stopPropagation();
});
</script>
</body>
</html>
event.stopPropagation()
防止事件冒泡。通过以上方法,可以有效地实现单击外部区域关闭自定义快捷菜单的功能,并提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云