javascript 当我在导航栏外单击时如何关闭导航栏?

nvbavucw  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(129)
<span class="hamburger" id="hamburger" onclick="openNav()">
<nav id="nav-bar" class="nav-bar">
    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</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函数不应该调用。我该如何解决这个问题?

wvt8vs2t

wvt8vs2t1#

navBar = document.getElementById('nav-bar');
            document.onclick = function(clickEvent) {
              var clickover = clickEvent.target;
                
                if (!document.getElementById('nav-bar').contains(clickover) && clickover.id!="hamburger" ){
                    navBar.classList.remove('active');
                     document.body.style.backgroundColor = '#fefefe';
                }
            }
            function openNav() {
                navBar.classList.add('active');
                document.body.style.backgroundColor = 'rgba(0,0,0,0.4)';
            }
            function closeNav() {
              
                navBar.classList.remove('active');
                document.body.style.backgroundColor = '#fefefe';
            }
ul li{
  margin:5px;
  display:inline-block;
}

.closebtn{
cursor:pointer;
}
<span class="hamburger" id="hamburger" onclick="openNav()">open Nav</span>
<nav id="nav-bar" class="nav-bar">
    <a class="closebtn" onclick="closeNav()">&times;</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>

相关问题