我是一名新手Web开发人员,当然我遇到了问题哈哈。希望有人可以提供建议。我试图构建一个响应式移动导航栏,但是当我单击菜单按钮并更改屏幕大小时,导航栏消失了。我认为这与javascript中的事件处理程序有关。有人可以帮助我,让我知道我哪里错了吗?
const navbar = document.getElementById('navbar')
document.getElementById('menubutton').addEventListener('click', myFunction);
function myFunction(event){
if (navbar.style.display==="block") {
navbar.style.display ="none";
} else {
navbar.style.display="block";
}
}
body{
margin: 0 auto;
width: 100%;
}
.headermenu{
display: flex;
justify-content:space-between;
align-items: center;
width: 100%;
}
.buttonstyling{
background-color: black;
color: white;
font-size: 2em;
padding: 20px;
border: none;
width: 100%;
text-align: left;
}
.navbar{
display: none;
background-color: black;
}
.navbar a{
text-decoration: none;
color: white;
display: block;
background-color: black;
padding: 15px;
}
img {
width: 100%;
}
#logoheader{
width: 60%;
}
@media (min-width: 768px){
.buttonstyling{
display: none;
}
.navbar{
display: flex;
background-color: white;
justify-content: space-around;
}
.navbar a{
background-color: white;
color: black;
}
}
<header>
<div class="headermenu">
<button type="button" id="menubutton" class="buttonstyling">
Menu
</button>
</div>
<nav class="navbar" id="navbar">
<a href="#">Home</a>
<a href="">About</a>
<a href="">Services</a>
<a href="">Work With Me</a>
<a href="">Blog</a>
<a href="">Contact</a>
</nav>
</header>
答案 0 :(得分:0)
当您使用JavaScript硬设置style.display = none
时,该元素现在将在每个屏幕尺寸中都具有该样式,并且将忽略它之后的所有冲突CSS规则。您要做的是创建一个可以添加和删除的类,该类具有仅适用于某些屏幕尺寸的规则。
在此示例中,我添加了类expanded
,该类将不会应用于媒体查询中的任何元素。相反,navbar
将退回到display: flex
。
const navbar = document.getElementById('navbar')
document.getElementById('menubutton').addEventListener('click', myFunction);
function myFunction(event){
if (navbar.classList.contains('expanded')) {
navbar.classList.remove('expanded');
} else {
navbar.classList.add('expanded');
}
}
body{
margin: 0 auto;
width: 100%;
}
.headermenu{
display: flex;
justify-content:space-between;
align-items: center;
width: 100%;
}
.buttonstyling{
background-color: black;
color: white;
font-size: 2em;
padding: 20px;
border: none;
width: 100%;
text-align: left;
}
.navbar{
display: none;
background-color: black;
}
.expanded {
display: block;
}
.navbar a{
text-decoration: none;
color: white;
display: block;
background-color: unset;
padding: 15px;
}
img {
width: 100%;
}
#logoheader{
width: 60%;
}
@media (min-width: 768px){
.buttonstyling{
display: none;
}
.navbar{
display: flex;
transform: unset;
background-color: white;
justify-content: space-around;
}
.navbar a{
background-color: white;
color: black;
}
}
<header>
<div class="headermenu">
<button type="button" id="menubutton" class="buttonstyling">
Menu
</button>
</div>
<nav class="navbar" id="navbar">
<a href="#">Home</a>
<a href="">About</a>
<a href="">Services</a>
<a href="">Work With Me</a>
<a href="">Blog</a>
<a href="">Contact</a>
</nav>
</header>