2017-08-30 69 views
0

我用flexbox创建了一个简单触发器的响应式菜单,但遇到了问题。在其中一个媒体查询中,我将UL降到div以下,其中包含logotrigger,并更改它的display:none,直到点击触发器。响应式Flex菜单

当我试图将UL设置为打开状态时,当我给它添加边距和填充时,它增加了nav的整体大小,因此您可以指出隐藏的内容。由于元素是隐藏的,在触发打开状态之前,边界和填充不应该有效吗?

我发现通过添加边距和填充到LI工作,但我觉得这是一个骗子。

$(function() { 
 
\t 
 
\t $('.trigger').click(function() { 
 
\t \t $('.mainNav').toggleClass('show'); 
 
\t }); 
 
\t 
 
\t 
 
});
* { 
 
\t margin: 0; 
 
\t padding: 0; 
 
\t list-style-type: none; 
 
} 
 

 
body { 
 
\t font-size: 17px; 
 
\t color: white; 
 
} 
 

 
nav { 
 
\t height: 100%; 
 
\t width: 100%; 
 
\t background-color: #333; 
 
} 
 

 
.nav-fixedWidth { 
 
\t height: inherit; 
 
\t min-height: 70px; 
 
\t width: 960px; 
 
\t margin: 0 auto; 
 
\t display: flex; 
 
\t flex-flow: row; 
 
} 
 

 
.logo-and-trigger { 
 
\t display: flex; 
 
\t justify-content: space-between; 
 
} 
 

 
.logo { 
 
\t content: ''; 
 
\t height: 50px; 
 
\t width: 50px; 
 
\t background-color: #f1f1f1; 
 
\t position: relative; 
 
\t margin: 8px 0; 
 
} 
 

 
.trigger { 
 
\t content: ''; 
 
\t height: 50px; 
 
\t width: 50px; 
 
\t background-color: #f1f1f1; 
 
\t display: none; 
 
\t position: relative; 
 
\t margin: 8px 0; 
 
} 
 

 
.mainNav{ 
 
\t display: flex; 
 
\t width: 200px; 
 
\t justify-content: space-between; 
 
\t margin: 20px 0px; 
 
\t margin-left: auto; 
 
\t overflow: hidden; 
 
\t transition:max-height .3s ease; 
 
} 
 

 
@media screen and (max-width: 960px) { 
 
\t 
 
\t .nav-fixedWidth { 
 
\t \t width: 100vw; 
 
\t } 
 
} 
 

 
@media screen and (max-width: 900px) { 
 
\t 
 
\t .nav-fixedWidth { 
 
\t \t flex-flow: column; \t 
 
\t } 
 
\t 
 
\t .mainNav { 
 
\t \t margin:0; 
 
\t \t width: 100%; 
 
\t \t display: block; 
 
\t \t max-height: 0; 
 
\t } 
 
\t 
 
\t .mainNav li { 
 
\t \t margin: 20px; 
 
\t \t padding: 20px; 
 
\t \t margin-left: 0; 
 
\t \t width: 100%; 
 
\t \t padding-left: 0; 
 
\t } 
 
\t 
 
\t .show { 
 
\t \t max-height: 20em; 
 
\t } 
 
\t 
 
\t .trigger { 
 
\t \t display: flex; 
 
\t } 
 
\t 
 
\t 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<nav> 
 
\t <div class="nav-fixedWidth"> 
 
\t \t <div class="logo-and-trigger"> 
 
\t \t \t <div class="logo"></div> 
 
\t \t \t <div class="trigger"></div> 
 
\t \t </div> 
 
\t \t <ul class="mainNav"> 
 
\t \t \t <li>Link 1</li> 
 
\t \t \t <li>Link 2</li> 
 
\t \t \t <li>Link 3</li> 
 
\t \t </ul> 
 
\t </div> 
 
</nav>

+0

_“由于元素被隐藏”_ - 不是,您只是给它一个最大高度为0. – CBroe

回答

1

我认为当你使用,你不改上行,显示 “$ toggleClass( '秀 ')(' mainNav。')。”:没有因此空间即使触发未被点击,也会在页面上为UL分配。这就是为什么你可以看到UL元素上的边距和填充。

如果你想保持toggleClass,您可以应用margin和padding的CSS类.show

或者,如果你想添加margin和padding在UL,您必须使用$(“ mainNav”) .css({'display':'block'})和$('。mainNav').css({'display':'none'})并且不使用toggleClass。

+0

非常感谢! –