如何增强你网站的用户体验和SEO:HTML5实现自定义下拉框

16 min read

好的,以下是一个简单的HTML5自定义下拉框的示例:

<!DOCTYPE html>
<html>
<head>
	<title>Custom Dropdown</title>
</head>
<body>
	<label for="fruits">Choose a fruit:</label>
	<div class="dropdown">
		<select id="fruits" name="fruits">
			<option value="apple">Apple</option>
			<option value="banana">Banana</option>
			<option value="orange">Orange</option>
			<option value="pear">Pear</option>
			<option value="watermelon">Watermelon</option>
		</select>
		<div class="dropdown-content">
			<a href="#" onclick="selectFruit('apple')">Apple</a>
			<a href="#" onclick="selectFruit('banana')">Banana</a>
			<a href="#" onclick="selectFruit('orange')">Orange</a>
			<a href="#" onclick="selectFruit('pear')">Pear</a>
			<a href="#" onclick="selectFruit('watermelon')">Watermelon</a>
		</div>
	</div>

	<script>
		function selectFruit(fruit) {
			document.getElementById("fruits").value = fruit;
		}

		// Function to toggle dropdown content visibility
		function toggleDropdown() {
			document.getElementById("fruits").classList.toggle("active");
			document.querySelector(".dropdown .dropdown-content").classList.toggle("show");
		}

		// Close the dropdown if the user clicks outside of it
		window.onclick = function(event) {
			if (!event.target.matches('.dropdown-btn')) {
				var dropdowns = document.getElementsByClassName("dropdown-content");
				for (var i = 0; i < dropdowns.length; i++) {
					var openDropdown = dropdowns[i];
					if (openDropdown.classList.contains('show')) {
						openDropdown.classList.remove('show');
					}
				}
			}
		}
	</script>

	<style>
		/* Styling for the dropdown */
		.dropdown {
			position: relative;
			display: inline-block;
			margin: 20px;
		}

		/* Styling for the dropdown button */
		#fruits {
			display: none;
		}

		/* Styling for the dropdown content */
		.dropdown-content {
			display: none;
			position: absolute;
			z-index: 1;
			background-color: #f9f9f9;
			min-width: 160px;
			box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
		}

		/* Styling for the dropdown content links */
		.dropdown-content a {
			color: black;
			padding: 12px 16px;
			text-decoration: none;
			display: block;
			cursor: pointer;
		}

		/* Styling for the dropdown content links on hover */
		.dropdown-content a:hover {
			background-color: #f1f1f1;
		}

		.active .dropdown-content {
			display: block;
		}
	</style>
</body>
</html>

这个示例中,我们使用了一个 <select> 标签和一个自定义的 <div> 标签,同时在该自定义的 <div> 中嵌套了一堆 <a> 标签作为下拉框的选项。然后,我们使用JavaScript编写了一些函数来操作下拉框的行为,例如点击某个选项时将其值设置为所选值,以及当用户点击页面其他位置时隐藏下拉框内容。最后,我们使用CSS对下拉框进行了简单的样式设置。