【发布时间】:2020-02-20 01:30:47
【问题描述】:
我已经用这个 javascript 导航尝试了几个小时,我研究了很多网站,包括 w3schools、codepen 和 css 技巧,以及许多其他网站,我花了几个小时阅读堆栈,一切都有很大帮助,现在我差不多完成了,我需要一些帮助才能使这个菜单正常工作。
本质上,它是一个子导航菜单,当您单击向下箭头按钮时会保持打开状态,当您单击页面上的任何位置时会关闭。有时有效,有时无效。
菜单有两个链接: 论坛 1 / 向下箭头按钮和 论坛 2 / 向下箭头按钮
我有时可以通过单击向下箭头按钮让论坛 1 向下箭头按钮打开子导航,但我根本无法让论坛 2 向下箭头按钮触发子导航。
我不确定这是我拥有 css 的方式,还是什么。
我正在提供包含 css、html 和 javascript 的完整菜单,
就像我说的,有时我可以让第一个向下箭头按钮打开子导航,但仅此而已。你能帮我解决这个问题吗?
这是导航菜单的样式
body {
font-family: Arial, Helvetica, sans-serif;
margin: 0;
}
.navbar {
overflow: hidden;
background-color: #18143c;
}
.navbar a {
float: left;
font-size: 16px;
color: white;
text-align: center;
padding: 14px 7px 14px 16px;
text-decoration: none;
}
.subnav {
float: left;
overflow: auto;
}
.subnav .subnavbtn {
font-size: 16px;
border: none;
outline: none;
color: white;
padding: 14px 5px;
background-color: inherit;
font-family: inherit;
margin: 0;
margin-right:26px;
}
.navbar a:hover, .subnav:hover .subnavbtn {
background-color: #46485c;
}
.subnav-content-1 {
display: none;
position: absolute;
left: 0;
background-color: #46485c;
width: 100%;
z-index: 1;
overflow:auto;
}
.subnav-content-1 a {
float: left;
color: white;
text-decoration: none;
padding: 10px 10px;
}
.subnav-content-1 a:hover {
background-color: #eee;
color: black;
}
.show {display: block;}
这是导航菜单的 HTML
<div class="navbar">
<a href="#home"style="padding-left:6px;">Forums 1</a>
<div class="subnav">
<button onclick="myFunction()" class="subnavbtn"><i class="fa fa-caret-down"></i></button>
<div id="myDropdown" class="subnav-content-1">
<a href="#"style="margin-left:16px;">Test Main</a>
<a href="#">Test link 1</a>
<a href="#">Test link 1</a>
<a href="#">Test link 1</a>
</div>
</div>
<a href="#home"style="padding-left:6px;">Forums 2</a>
<div class="subnav">
<button onclick="myFunction()" class="subnavbtn"><i class="fa fa-caret-down"></i></button>
<div id="myDropdown" class="subnav-content-1">
<a href="#"style="margin-left:16px;">Test Main</a>
<a href="#">Test link 2</a>
<a href="#">Test link 2</a>
<a href="#">Test link 2</a>
</div>
</div>
</div>
这里是javascript
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.subnavbtn')) {
var dropdowns = document.getElementsByClassName("subnav-content-1");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
这里是 W3schools 上我一直在处理此菜单的页面的链接。 https://www.w3schools.com/code/tryit.asp?filename=GC3LUF0TLS6S
我想要做的是,让菜单正常工作,当您单击下拉箭头按钮时,它会打开子导航菜单,然后要关闭子导航,您只需单击页面上的任意位置。
这几乎行得通!请帮助我让它正常工作。
【问题讨论】:
标签: javascript html css menu navigation