问题
I want to make a responsive webpage. I want it to display a different nav based on the viewport. Here is the javascript that I have so far:
var shownav = document.getElementById('show-nav');
if (screen.width < "720"){
shownav.style.display = 'block';
}
But for some reason, it does not work. Can you please help me?
回答1:
You can achieve this without javascript by using a media-query:
#show-nav {
display: none;
background-color: red;
}
/* if screen width is smaller than 720px, #show-nav will be a block */
@media only screen and (max-width: 720px) {
#show-nav {
display: block;
}
}
<nav id="show-nav">
Navbar
</nav>
回答2:
You could use only css to do so.
DEMO (make it full page)
body{
margin: 0;
}
nav{
width: 100vw;
background:yellow;
}
@media only screen and (min-width: 720px){
nav{
background:red;
}
}
<nav>
<ul>
<li>Welcome</li>
</ul>
</nav
回答3:
@media only screen and (max-width: 720px) {
#show-nav {
display: block;
}
}
来源:https://stackoverflow.com/questions/64375491/how-do-i-make-the-navbar-responsive-depending-on-the-viewport