响应式导航栏失败
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了响应式导航栏失败相关的知识,希望对你有一定的参考价值。
我有一个导航栏,我希望它只有第一个元素Wakanda Team
和一个汉堡图标,当屏幕小于900px。但我不断得到其他元素如图所示。有人可以帮忙吗?
html:
<ul class="topnav" id="myTopnav">
<li style="float:left"><a href="#home" class="home">Wakanda Team</a></li>
<li><a><i class="material-icons">subdirectory_arrow_left</i> Sign out</a></li>
<li><a><i class="material-icons">exit_to_app</i> Sign in</a></li>
<li><a><i class="material-icons">person_add</i> Register</a></li>
<li><a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">☰</a></li>
</ul>
<p>Welcome to <%= title %></p>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
CSS:
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #FFFFFF;
position: fixed;
top: 0;
width: 100%;
}
li {
float: right;
}
li a {
display: block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover:not(.home){
background-color: #111;
text-decoration: none;
color: white;
}
li a .home:hover{
text-decoration: none;
}
.material-icons {
vertical-align: middle;
}
.topnav .icon {
display: none;
}
@media screen and (max-width: 900px) {
.topnav a:not(:first-child) {display: none;}
.topnav a.icon {
float: right;
display: block;
}
}
@media screen and (max-width: 900px) {
.topnav.responsive {position: relative;}
.topnav.responsive .icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
}
答案
试试这个吧
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #FFFFFF;
position: fixed;
top: 0;
width: 100%;
}
li {
float: right;
}
li a {
display: block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover:not(.home){
background-color: #111;
text-decoration: none;
color: white;
}
li a .home:hover{
text-decoration: none;
}
.material-icons {
vertical-align: middle;
}
.topnav .icon {
display: none;
}
@media screen and (max-width: 900px) {
.topnav li:not(:first-child) {
display: none;
}
.topnav li.icon {
display: block;
}
.topnav a.icon {
float: right;
display: block;
}
}
<ul class="topnav" id="myTopnav">
<li style="float:left"><a href="#home" class="home">Wakanda Team</a></li>
<li><a><i class="material-icons">subdirectory_arrow_left</i> Sign out</a></li>
<li><a><i class="material-icons">exit_to_app</i> Sign in</a></li>
<li><a><i class="material-icons">person_add</i> Register</a></li>
<li class="icon"><a href="javascript:void(0);" style="font-size:15px;" onclick="myFunction()">☰</a></li>
</ul>
<p>Welcome to <%= title %></p>
以上是关于响应式导航栏失败的主要内容,如果未能解决你的问题,请参考以下文章
没有 Javascript 的响应式导航栏,仅使用 HTML 和 CSS