【发布时间】:2019-03-05 00:41:33
【问题描述】:
我在顶部导航栏中有项目。随着屏幕尺寸变小,我想将不太重要的东西移到汉堡菜单中。我想先移动不太重要的项目,而不仅仅是从右边开始,所以要按确定的顺序。
我是使用 CSS 媒体查询来实现的。通过隐藏顶部项目并同时在汉堡菜单中显示菜单。问题是我必须有两次,一次在顶部,一次在汉堡。也可以在这里找到:https://jsfiddle.net/fqxndrhy/
document.getElementById('hamburger').onclick = function() {
document.getElementById('mobile_menu').classList.toggle('show');
}
body {
margin: 0;
}
nav {
display: flex;
position: sticky;
left: 0;
top: 0;
width: 100vw;
}
nav>section {
border: 1px solid red;
}
#mobile_menu {
display: none;
position: fixed;
top: 1cm;
right: 0;
border: 1px solid green;
display: none;
flex-direction: column;
color: black;
background-color: white;
}
#mobile_menu.show {
display: flex;
}
#desktop1 {
flex: 1;
}
/* hiding certain items at smaller resolutions */
#mobile1,
#mobile2,
#mobile3,
#mobile4,
#mobile5,
#hamburger {
display: none;
}
@media (max-width: 1000px) {
#desktop2 {
display: none;
}
#mobile2,
#hamburger {
display: initial;
}
}
@media (max-width: 900px) {
#desktop5 {
display: none;
}
#mobile5 {
display: initial;
}
}
@media (max-width: 800px) {
#desktop3,
#desktop4 {
display: none;
}
#mobile3,
#mobile4 {
display: initial;
}
}
<nav>
<section id="desktop1">desktop1</section>
<section id="desktop2">desktop2</section>
<section id="desktop3">desktop3</section>
<section id="desktop4">desktop4</section>
<section id="desktop5">desktop5</section>
<button id="hamburger">☰</button>
</nav>
<div id="mobile_menu">
<section id="mobile1">mobile1</section>
<section id="mobile2">mobile2</section>
<section id="mobile3">mobile3</section>
<section id="mobile4">mobile4</section>
<section id="mobile5">mobile5</section>
</div>
Open it in separate window and shrink browser width to hide top items. Items are hiding in random order and appearing in hamburger menu (desktop2 at 1000px width, desktop5 at 900px width, desktop3 and desktop4 at 800px width
是否有可能避免这种重复?我做了一些尝试,但它们非常复杂,我正在寻找一个简单、强大的解决方案?
【问题讨论】:
-
如果你想用纯 css 实现它,你无法避免重复。但是你可以使用 JS。例如,使用窗口上的侦听器调整大小。或者您也可以通过在桌面菜单上循环在文档就绪侦听器处使用 javascript 创建菜单的移动部分,这样您就不必在 html 中复制菜单
标签: javascript html css