
1. 引言
在现代web应用中,下拉菜单(dropdown menu)是一种常见的ui组件。为了提供良好的用户体验,当用户点击下拉菜单外部的任何区域时,通常需要自动关闭已打开的菜单。然而,实现这一功能时,开发者常会遇到事件冲突和逻辑判断错误等问题。本教程将提供一个清晰、高效且易于理解的纯javascript解决方案。
2. HTML结构
首先,我们需要一个标准的HTML结构来表示下拉菜单。它通常包含一个触发器(例如标题)和一个包含选项的菜单列表。
Choose category
在这个结构中:
- .dropdown 是整个下拉菜单的容器。
- .dropdown--title 是点击后触发菜单显示/隐藏的元素。
- .categories.menu 是实际的下拉选项列表。
3. CSS样式
CSS用于控制下拉菜单的外观和显示/隐藏动画。关键在于通过一个show类来控制菜单的可见性,利用max-height属性配合transition实现平滑的展开和收起效果。
.dropdown {
position: relative;
}
.dropdown::before {
content: "+";
position: absolute;
width: 1.5rem;
height: 1.5rem;
top: 15px;
right: 0;
color: var(--cbl); /* 假设定义了CSS变量 */
}
.dropdown .dropdown--title {
padding: 0.75rem;
width: 100%;
cursor: pointer;
}
.dropdown .menu {
cursor: pointer;
max-height: 0; /* 初始隐藏状态,通过max-height实现折叠动画 */
overflow: hidden;
display: flex;
flex-direction: column;
position: absolute;
z-index: 12;
width: 100%;
top: 45px;
right: 0;
background-color: var(--cwh); /* 假设定义了CSS变量 */
transition: max-height 0.3s;
-webkit-transition: max-height 0.3s;
-moz-transition: max-height 0.3s;
-ms-transition: max-height 0.3s;
-o-transition: max










