代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>下拉菜单示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="dropdown">
<a href="#" onclick="toggleDropdown(event)">菜单</a>
<div id="dropdownContent" class="dropdown-content">
<a href="#">菜单项1</a>
<a href="#">菜单项2</a>
<a href="#">菜单项3</a>
</div>
</div>
<script>
function toggleDropdown(event) {
event.preventDefault(); // 阻止默认行为(防止页面跳转)
var dropdownContent = document.getElementById("dropdownContent");
dropdownContent.style.display = dropdownContent.style.display === "block" ? "none" : "block";
// 点击页面任意位置关闭下拉菜单
document.addEventListener('click', function(e) {
var dropdown = document.querySelector('.dropdown');
if (!dropdown.contains(e.target)) {
dropdownContent.style.display = 'none';
}
});
}
</script>
</body>
</html>
styles.css
.dropdown {
position: relative;
display: inline-block;
}
.dropdown {
min-width: 150px;
/* 设置一个合适的最小宽度 */
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #f1f1f1;
}