<!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>&lt;h2&gt;动态添加下拉菜单&lt;/h2&gt;

&lt;div class=&quot;dropdown&quot; id=&quot;myDropdown&quot;&gt;
	&lt;button&gt;菜单&lt;/button&gt;
&lt;/div&gt;

&lt;script&gt;
	// 创建一个数组来存储菜单项
	var menuItems = [
		'首页',
		'产品',
		'服务',
		'关于我们',
		'联系我们'
	];

	// 获取菜单容器
	var dropdown = document.getElementById(&quot;myDropdown&quot;);

	// 创建一个下拉菜单
	var dropdownContent = document.createElement(&quot;div&quot;);
	dropdownContent.classList.add(&quot;dropdown-content&quot;);

	// 将菜单项添加到下拉菜单中
	for (var i = 0; i &lt; menuItems.length; i++) {
		var menuItem = document.createElement(&quot;a&quot;);
		menuItem.href = &quot;#&quot;;
		menuItem.textContent = menuItems[i];
		dropdownContent.appendChild(menuItem);
	}

	// 将下拉菜单添加到菜单容器中
	dropdown.appendChild(dropdownContent);
&lt;/script&gt;
</code></pre>
</body>
</html>

原文地址: https://www.cveoy.top/t/topic/oLfg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录