我正在尝试制作一个可点击的菜单,并尝试使用javascript和css进行切换,但我想让每个也有子菜单也切换,我尝试主要使用javascript,如何我可以做到吗?
这是我的代码:
HTML:
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">|||</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<div class="child-dropdown">
<a href="#">Sublink 1</a>
<a href="#">Sublink 1</a>
<a href="#">Sublink 1</a>
</div>
<a href="#">Link 3</a>
<div class="child-dropdown">
<a href="#">Sublink 1</a>
<a href="#">Sublink 1</a>
<a href="#">Sublink 1</a>
</div>
</div>
</div>
Javascript:
<script>
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
CSS
.dropbtn {
background-color: #cc0000;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
position:relative;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #e6e6e6;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #e6e6e6;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #cc0000}
.show {display:block;}
答案 0 :(得分:0)
使用给定的标记,#myDropdown
内的链接甚至不需要javascript:你可以像这样使用:focus
伪类
#myDropdown a:focus + div {
display: block;
}
当然,只要你的链接是专注的,这就有效:如果你想能够拥有其他重点(或打开许多子菜单),你可以使用一些javascript,如
[].forEach.call(document.querySelectorAll('#myDropdown > a'), function(l) {
l.addEventListener('click', function() {
l.classList.toggle('open');
}, false);
});
或#myDropdown
上的事件委派
document.getElementById('myDropdown').addEventListener('click', function(evt) {
var target = evt.target;
if (target.nodeName.toLowerCase() === 'a') {
target.classList.toggle('open');
}
}, false);
和这个CSS
#myDropdown div { display: none; }
#myDropdown a.open + div { display: block; }