gpt4 book ai didi

javascript - 响应式 Flex 菜单

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:09 24 4
gpt4 key购买 nike

我使用 flexbox 创建了一个带有简单触发器的响应式菜单,但我遇到了一个问题。在其中一个媒体查询中,我将 UL 放到包含 logotriggerdiv 下面并更改它的 display:none 直到触发器被点击。

当我试图为它的打开状态设置 UL 的样式时,当我给它 margin 和 padding 时,它增加了 nav 的整体大小所以你可以告诉一些事情躲起来了。既然元素是隐藏的,那么 margin 和 padding 不应该在打开状态被触发之前不起作用吗?

我通过向 LI 添加边距和填充找到了解决方法,但我觉得这是一种作弊。

$(function() {

$('.trigger').click(function() {
$('.mainNav').toggleClass('show');
});


});
* {
margin: 0;
padding: 0;
list-style-type: none;
}

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

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

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

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

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

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

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

@media screen and (max-width: 960px) {

.nav-fixedWidth {
width: 100vw;
}
}

@media screen and (max-width: 900px) {

.nav-fixedWidth {
flex-flow: column;
}

.mainNav {
margin:0;
width: 100%;
display: block;
max-height: 0;
}

.mainNav li {
margin: 20px;
padding: 20px;
margin-left: 0;
width: 100%;
padding-left: 0;
}

.show {
max-height: 20em;
}

.trigger {
display: flex;
}


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<div class="nav-fixedWidth">
<div class="logo-and-trigger">
<div class="logo"></div>
<div class="trigger"></div>
</div>
<ul class="mainNav">
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</div>
</nav>

最佳答案

我认为当您使用“$('.mainNav').toggleClass('show');”时,您不会将 UL 更改为 display:none 因此即使触发器在页面上为 UL 分配了空间没有被点击。这就是为什么您可以在 UL 元素上看到边距和填充。

如果你想保留 toggleClass,你可以在 CSS class .show 上应用 margin 和 padding

或者如果你想在 UL 上添加边距和填充,你必须使用 $('.mainNav').css({'display':'block'}) 和 $('.mainNav').css( {'display':'none'}) 并且不要使用 toggleClass。

关于javascript - 响应式 Flex 菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45968126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com