<span class="hamburger" id="hamburger" onclick="openNav()">
<nav id="nav-bar" class="nav-bar">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Help</a></li>
<li><a href="#">Address</a></li>
</ul>
</nav>
<script>
navBar = document.getElementById('nav-bar');
document.onclick = function(clickEvent) {
if(clickEvent.target.id !== 'nav-bar'){
navBar.classList.remove('active');
}
}
function openNav() {
navBar.classList.toggle('active');
document.body.style.backgroundColor = 'rgba(0,0,0,0.4)';
}
function closeNav() {
navBar.classList.remove('active');
document.body.style.backgroundColor = '#fefefe';
}
</script>
实际上,我在点击导航栏外时试图关闭导航栏。当我调用onclick openNav函数时,同时也调用了document.onclick函数。这将导致我的导航栏没有打开。当我调用openNav onclick函数时,document.onclick函数不应该调用。我该如何解决这个问题?
1条答案
按热度按时间wvt8vs2t1#