在JavaScript中创建一个世界国家下拉菜单涉及到几个基础概念,包括HTML、CSS和JavaScript的使用。下面是一个简单的示例,展示如何实现这一功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Country Dropdown</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="dropdown">
<button onclick="toggleDropdown()" class="dropbtn">Select a Country</button>
<div id="myDropdown" class="dropdown-content">
<!-- JavaScript will populate this -->
</div>
</div>
<script src="script.js"></script>
</body>
</html>
.dropdown {
position: relative;
display: inline-block;
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
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;}
const countries = [
"Afghanistan", "Albania", "Algeria", /* ... list all countries ... */
"Zimbabwe"
];
function populateDropdown() {
const dropdownContent = document.getElementById("myDropdown");
countries.forEach(country => {
const option = document.createElement("a");
option.href = "#";
option.textContent = country;
dropdownContent.appendChild(option);
});
}
function toggleDropdown() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onload = populateDropdown;
通过上述方法,可以创建一个功能齐全且用户友好的世界国家下拉菜单。
领取专属 10元无门槛券
手把手带您无忧上云