HTML+CSS+JavaScript下拉菜单代码
时间: 2024-09-30 14:13:39 浏览: 31
HTML+CSS+JS实现的下拉菜单源码
在HTML、CSS和JavaScript的组合下创建一个基本的下拉菜单可以分为几个步骤:
**HTML结构**:
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="dropdown">
<button class="dropbtn">下拉菜单</button>
<div class="dropdown-content">
<a href="#">选项1</a>
<a href="#">选项2</a>
<a href="#">选项3</a>
</div>
</div>
<script src="scripts.js"></script>
</body>
</html>
```
**CSS样式 (styles.css)**:
```css
.dropdown {
position: relative;
display: inline-block;
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
border: none;
cursor: pointer;
}
.dropdown-content {
display: none;
position: absolute;
min-width: 160px;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #f1f1f1;
}
.show {
display: block;
}
```
**JavaScript代码 (scripts.js)**:
```javascript
document.querySelector('.dropbtn').addEventListener('click', function() {
this.classList.toggle('show');
});
```
在这个例子中,当你点击按钮时,`dropdown-content` 就会通过 JavaScript 的 `classList.toggle` 属性切换显示/隐藏。
阅读全文