我创建了一个响应式导航栏,其中包含使用flex的切换菜单,但在移动视图中不会折叠。
我还包括了Font Awesome提供的toggle btn,并将其集成到html头中的我的项目中。
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
</head>
这是导航栏的代码。
<div class="Navbar3">
<div class="Navbar__Link Navbar__Link-brand">
</div>
<div class="Navbar__Link Navbar__Link-toggle">
<i class="fas fa-bars"></i>
</div>
<nav class="Navbar__Items">
<div class="Navbar__Link active">
All
</div>
<div class="Navbar__Link">
<a href="graphic.html">Design</a>
</div>
<div class="Navbar__Link">
<a href="animation.html">Animation</a>
</div>
</nav>
</div>
这是导航栏的css
.Navbar3 {
background-color: #2262AD;
display: flex;
padding: 16px;
font-family: sans-serif;
color: white;
justify-content: center;
}
.Navbar__Link {
padding-right: 25px;
font-weight: bold;
align-self: center;
justify-content: center;
cursor: pointer;
}
.Navbar__Items {
display: flex;
}
.Navbar__Link-toggle {
display: none;
}
@media only screen and (max-width: 768px) {
.Navbar__Items,
.Navbar3 {
flex-direction: column;
}
.Navbar__Items {
display: none;
}
.Navbar__Items--right {
margin-left: 0;
}
.Navbar__ToggleShow {
display: flex;
}
.Navbar__Link-toggle {
align-self: flex-end;
display: initial;
position: absolute;
cursor: pointer;
}
}
.Navbar__Link:hover{
color: black;
}
.active {
color: black;
text-decoration: underline;
}
以下是用于切换的js
function classToggle() {
const navs = document.querySelectorAll('.Navbar__Items')
navs.forEach(nav => nav.classList.toggle('Navbar__ToggleShow'));
}
document.querySelector('.Navbar__Link-toggle')
.addEventListener('click', classToggle);
答案 0 :(得分:0)
当我在浏览器中测试代码时,您的代码似乎可以正常工作。如果专门用于移动设备的视图不起作用,请尝试添加
<meta name="viewport" content="width=device-width, initial-scale=1.0">
对您的脑袋。有关更多信息,请访问MDN。
希望这能解决您的问题。
答案 1 :(得分:0)
发现了这个问题。这是由我的js中的最后两行代码引起的。评论了他们,导航正常!
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
var captionText = document.getElementById("caption");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
//dots[slideIndex-1].className += " active";
//captionText.innerHTML = dots[slideIndex-1].alt;
}