HTML 动态添加下拉菜单:JavaScript 实现
<!DOCTYPE html>
<html>
<head>
<title>动态添加下拉菜单</title>
<style type="text/css">
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
z-index: 1;
}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #f1f1f1;
}
</style>
</head>
<body>
<pre><code><h2>动态添加下拉菜单</h2>
<div class="dropdown" id="myDropdown">
<button>菜单</button>
</div>
<script>
// 创建一个数组来存储菜单项
var menuItems = [
'首页',
'产品',
'服务',
'关于我们',
'联系我们'
];
// 获取菜单容器
var dropdown = document.getElementById("myDropdown");
// 创建一个下拉菜单
var dropdownContent = document.createElement("div");
dropdownContent.classList.add("dropdown-content");
// 将菜单项添加到下拉菜单中
for (var i = 0; i < menuItems.length; i++) {
var menuItem = document.createElement("a");
menuItem.href = "#";
menuItem.textContent = menuItems[i];
dropdownContent.appendChild(menuItem);
}
// 将下拉菜单添加到菜单容器中
dropdown.appendChild(dropdownContent);
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/oLfg 著作权归作者所有。请勿转载和采集!