【发布时间】:2021-02-25 02:56:44
【问题描述】:
我一直在使用 html、css 和 javascript 制作一个简单的水平导航栏。导航栏包含一个下拉菜单(名为更多)。单击“更多”菜单会导致隐藏链接(垂直)显示在“更多”标题下方,再次单击会再次隐藏链接。
我将导航栏中所有链接的边距设置为 2px(在 css 文件中),但链接之间的距离似乎不一致。具体来说,点击更多后,选项4和5之间的距离,以及选项5和6之间的距离,与其他链接之间的距离是不同的。你知道是什么导致了这个问题吗?
function clickMoreMenu() {
var x = document.getElementById("hiddenlinks");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
#navbar {
display: block;
width: 425px;
margin-left: auto;
margin-right: auto;
margin-bottom: 20px;
}
.navoption {
text-align: center;
display: block;
float: left;
}
#moremenu {
display: block;
}
#hiddenlinks {
display: none;
position: absolute;
z-index: 1;
margin-top: 0px;
}
#navbar a {
display: block;
text-align: center;
text-decoration: none;
padding-top: 10px;
padding-bottom: 10px;
width: 100px;
color: Blue;
background: Yellow;
border-style: solid;
border-color: Blue;
border-width: 1px;
margin: 2px;
}
#navbar a.currentpage {
color: DarkBlue;
background: Gold;
}
#navbar a:hover {
background: Blue;
color: Yellow;
}
h1 {
color: blue;
text-align: center;
}
.clearleft {
clear: left;
}
<h1>Distance Test</h1>
<nav id="navbar">
<div class="navoption">
<a href="index.html" class="currentpage">Index</a>
</div>
<div class="navoption">
<a href="option2.html">Option 2</a>
</div>
<div class="navoption">
<a href="option3.html">Option 3</a>
</div>
<div class="navoption" id="moremenu">
<a href="javascript:void(0);" onclick="clickMoreMenu()">More...</a>
<div id="hiddenlinks">
<a href="option4.html">Option 4</a>
<a href="option5.html">Option 5</a>
<a href="option6.html">Option 6</a>
</div>
</div>
</nav>
<div class="clearleft">Some text.</div>
【问题讨论】:
-
考虑不再使用浮动进行布局?考虑将 flexbox 用于列/行等一维布局?
-
你已经被页边距压扁了。见docs 和this question
-
@chazsolo 折叠边距,就是这样。一种可能的解决方案是设置两个边距而不是四个边距,例如设置 margin-right 和 margin-bottom 但不设置 margin-left 或 margin-top。
标签: javascript html css