基于CSS或JavaScript的下拉菜单
# 基于CSS或JavaScript的下拉菜单
## 概述
下拉菜单是一种常见的用户界面元素,用于在页面上以级联方式展示有限数量的信息。在这个例子中,我们将讨论如何使用 CSS 和 JavaScript 实现下拉菜单。
## 实现
### 1. HTML
首先,创建一个包含以下结构的HTML:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>基于CSS或JavaScript的下拉菜单</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="dropdown">
<select>
<option value="" disabled selected>请选择一个选项</option>
<option value="option1">选项1</option>
<option value="option2">选项2</option>
<option value="option3">选项3</option>
<option value="option4">选项4</option>
</select>
</div>
<script src="script.js"></script>
</body>
</html>
### 2. CSS
在 `styles.css` 文件中,创建一个自定义样式:
```css
.dropdown select {
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
color: #333;
font-size: 16px;
height: 40px;
padding: 10px;
width: 200px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.dropdown select:focus {
outline: none;
border-color: #999;
}
.dropdown::before,
.dropdown::after {
content: "";
position: absolute;
top: 16px;
right: 10px;
width: 0;
height: 0;
border: 6px solid transparent;
border-color: #333 transparent transparent transparent;
}
.dropdown::before {
z-index: 1;
}
.dropdown::after {
margin-top: 8px;
z-index: 0;
}
.dropdown select:focus ~::before {
border-color: #999 transparent transparent transparent;
}
.dropdown select:focus ~::after {
margin-top: 0px;
border-color: transparent transparent #999 transparent;
}
### 3. JavaScript
在 `script.js` 文件中,编写JavaScript代码:
```javascript
document.addEventListener('DOMContentLoaded', function () {
const dropdown = document.querySelector('.dropdown');
const select = dropdown.querySelector('select');
function openDropdown() {
dropdown.classList.add('open');
}
function closeDropdown() {
dropdown.classList.remove('open');
}
select.addEventListener('change', function () {
closeDropdown();
const selectedOption = select.options[select.selectedIndex].value;
console.log(`Selected option: ${selectedOption}`);
});
dropdown.addEventListener('click', function (event) {
event.stopPropagation();
});
document.addEventListener('click', function (event) {
if (!dropdown.contains(event.target)) {
closeDropdown();
}
});
openDropdown();
});
## 使用场景
下拉菜单适用于选择有限数量的不同选项。常用于:
- 单选框和复选框
- 列表选项
- 级联选项
## 示例
```html
<div class="dropdown">
<select>
<option value="" disabled selected>请选择一个选项</option>
<option value="option1">选项1</option>
<option value="option2">选项2</option>
<option value="option3">选项3</option>
<option value="option4">选项4</option>
</select>
</div>
在这个示例中,用户
领取专属 10元无门槛券
手把手带您无忧上云