📅  最后修改于: 2023-12-03 15:28:09.931000             🧑  作者: Mango
本文将介绍如何创建一个语义化 UI 完整的响应式菜单,基于 JavaScript 实现。可以学习到如何使用 HTML、CSS 和 JavaScript 开发一个优雅、兼容性好的响应式菜单,其中强调语义化和可访问性。具体实现过程参考以下步骤:
<nav class="menu">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li class="dropdown">
<button class="dropbtn">Services <i class="fa fa-caret-down"></i></button>
<div class="dropdown-content">
<a href="#">Web Design</a>
<a href="#">Web Development</a>
<a href="#">SEO</a>
</div>
</li>
<li><a href="#">Contact Us</a></li>
</ul>
</nav>
.menu {
display: flex;
justify-content: space-between;
align-items: center;
}
.menu ul {
display: flex;
list-style: none;
margin: 0;
padding: 0;
}
.menu li {
display: inline-block;
}
.menu a {
color: #fff;
text-decoration: none;
padding: 1rem;
}
.menu a:hover {
background-color: #444;
}
.dropdown {
position: relative;
}
.dropdown-content {
position: absolute;
z-index: 1;
display: none;
}
.dropdown-content a {
color: #000;
padding: 1rem;
}
.dropdown:hover .dropdown-content {
display: block;
}
.fa {
font-size: 0.8em;
margin-left: 0.2em;
}
@media screen and (max-width: 700px) {
.menu ul {
display: none;
}
.menu ul li {
display: block;
text-align: center;
background-color: #444;
margin-bottom: 1rem;
}
.menu ul li:last-child {
margin-bottom: 0;
}
.menu ul li a {
display: block;
padding: 1rem;
}
.dropdown {
position: static;
}
.dropdown-content {
display: none;
position: relative;
margin-bottom: 1rem;
}
.dropdown-content a {
background-color: #666;
color: #fff;
margin-bottom: 0.5rem;
}
.dropdown-content a:last-child {
margin-bottom: 0;
}
.icon {
display: inline-block;
margin-right: 0.5rem;
}
.dropdown .icon {
margin-right: 1rem;
}
}
// Toggle the dropdown on small screens
var toggleDropdown = function () {
var dropdowns = document.querySelectorAll(".dropdown-content");
for (var i = 0; i < dropdowns.length; i++) {
dropdowns[i].classList.toggle("show");
}
};
// Close the dropdown if the user clicks outside of it
window.onclick = function (event) {
if (!event.target.matches(".dropbtn")) {
var dropdowns = document.querySelectorAll(".dropdown-content");
for (var i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains("show")) {
openDropdown.classList.remove("show");
}
}
}
};
// Toggle menu icon on small screens
var toggleMenuIcon = function () {
var menuIcon = document.querySelector("#menu-icon");
menuIcon.classList.toggle("fa-bars");
menuIcon.classList.toggle("fa-times");
};
// Toggle menu on small screens
var toggleMenu = function () {
var menu = document.querySelector(".menu ul");
menu.classList.toggle("show");
};
// Add event listeners
var dropbtn = document.querySelector(".dropbtn");
var menuIcon = document.querySelector("#menu-icon");
dropbtn.addEventListener("click", toggleDropdown);
menuIcon.addEventListener("click", function () {
toggleMenuIcon();
toggleMenu();
});
通过以上步骤,我们成功创建了一个语义化 UI 完整的响应式菜单,可访问性和兼容性都较好。这里的代码仅仅是一个示例,可以根据实际情况对 HTML 和 CSS 进行调整。