下面提到的是导航菜单的HTML代码:
<nav role="navigation" class="nav">
<ul class="nav-items">
<li class="nav-item">
<a href="#" class="nav-link"><span>About Us</span></a>
</li>
<li class="nav-item dropdown">
<a href="#" class="nav-link"><span>Divisions</span></a>
<nav class="submenu">
<ul class="submenu-items">
<li class="submenu-item"><a href="#" class="submenu-link">Div 1</a></li>
<li class="submenu-item"><a href="#" class="submenu-link">Div 2</a></li>
</ul>
</nav>
</ul>
</nav>
我的JavaScript代码如下:
$(document).ready(function() {
[].slice.call(document.querySelectorAll('.dropdown .nav-link'))
.forEach(function(el) {
el.addEventListener('click', onClick, false);
});
function onClick(e){
e.preventDefault();
var el = this.parentNode;
el.classList.contains('show-submenu') ? hideSubMenu(el) : showSubMenu(el);
}
function showSubMenu(el){
el.classList.add('show-submenu');
document.addEventListener('click', function onDocClick(e){
e.preventDefault();
if(el.contains(e.target)){
return;
}
document.removeEventListener('click', onDocClick);
hideSubMenu(el);
});
}
function hideSubMenu(el){
el.classList.remove('show-submenu');
}
});
现在点击操作无效。有人请帮忙!我从一些在线教程中得到了这段代码。由于我是JavaScript的新手,请为我更正代码。提前谢谢。
答案 0 :(得分:0)
Your code works perfectly fine, might be the CSS class being incorrect which is causing the issue, can you recheck with the CSS class.
CSS:
.show-submenu > nav{
display:block;
}
.submenu{
display:none;
}
$(document).ready(function() {
[].slice.call(document.querySelectorAll('.dropdown .nav-link')).forEach(function(el) {
el.addEventListener('click', onClick, false);
});
function onClick(e) {
e.preventDefault();
var el = this.parentNode;
el.classList.contains('show-submenu') ? hideSubMenu(el) : showSubMenu(el);
}
function showSubMenu(el) {
el.classList.add('show-submenu');
document.addEventListener('click', function onDocClick(e) {
e.preventDefault();
if (el.contains(e.target)) {
return;
}
document.removeEventListener('click', onDocClick);
hideSubMenu(el);
});
}
function hideSubMenu(el) {
el.classList.remove('show-submenu');
}
});
.show-submenu > nav {
display: block;
}
.submenu {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav role="navigation" class="nav">
<ul class="nav-items">
<li class="nav-item">
<a href="#" class="nav-link"><span>About Us</span></a></li>
<li class="nav-item dropdown">
<a href="#" class="nav-link"><span>Divisions</span></a>
<nav class="submenu">
<ul class="submenu-items">
<li class="submenu-item"><a href="#" class="submenu-link">Div 1</a></li>
<li class="submenu-item"><a href="#" class="submenu-link">Div 2</a></li>
</ul>
</nav>
</ul>
</nav>