单击离开时如何删除导航栏的“活动”类别?

我对此有点陌生。我制作了一个导航栏,其中包含一个按钮,单击该按钮可切换“活动”类。我想做到这一点,以便当导航栏打开并单击时,它会删除“活动”类。虽然我使用了 eventListener (我对此一无所知,所以我用 Google 搜索)


function toggle() {

    var navButton = document.querySelector('.nav-btn-container');

    navButton.classList.toggle('active')

}


var navBar = document.querySelector('#nav-bar');

navBar.addEventListener('click', function(event){

    var isClickInside = navBar.contains(event.target);

    if (isClickInside && 

        document.querySelector('.nav-btn-container').classList.contains('active')){

        document.querySelector('.nav-btn-container').classList.remove('active');

    }

});

在 VS Code 中我没有收到任何错误,但在 Chrome 调试器中我收到以下错误:


Uncaught TypeError: Cannot read property 'addEventListener' of null

在事件函数中,我使用 document.querySelector('.nav-btn-container') 而不是 navBar,因为如果我将 navBar 声明移到toggle() 类之外(在第一行),当我单击按钮:


Uncaught ReferenceError: navButton is not defined

HTML:


<!DOCTYPE html>

<html>

<head>

    <script src="script.js"></script>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="style.css">

    <title>FCC: Product Landing Page</title>

</head>


<body>

    <header id="header">

        <img src="logo.png" alt="Logo" id="header-img">

        <button class="nav-btn-container" onclick="toggle()">

            <span class="nav-btn"></span>

        </button>

        <nav id="nav-bar">

             <ul class="nav-list">

                 <li class="nav-item"><a href="#features" class="nav- 

link">Features</a></li>

                 <li class="nav-item"><a href="#video" class="nav- 

link">Unboxing</a></li>

                 <li class="nav-item"><a href="#purchase" class="nav- 

link">Purchase</a></li>

                 <li class="nav-item"><a href="#reviews" class="nav- 

link">Reviews</a></li>

            </ul>

        </nav>

CSS: https: //pastebin.com/Zd7DFCca


慕桂英3389331
浏览 114回答 1
1回答

慕勒3428872

在head标签中插入此 jquery 参考脚本<head>&nbsp; &nbsp; <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>...</head>需要做的是添加鼠标单击event,单击时代码应检查单击是否在容器外部nav,如果为真,active将从容器中删除:在您的js脚本文件中,将js您发布的代码替换为:function toggle() {&nbsp; &nbsp; var navButton = document.querySelector('.nav-btn-container');&nbsp; &nbsp; navButton.classList.toggle('active')}$(document).mouseup(function (e) {&nbsp; &nbsp; var container = $("header");&nbsp; &nbsp; // if the target of the click isn't the container nor a descendant of the container&nbsp; &nbsp; if (!container.is(e.target) && container.has(e.target).length === 0) {&nbsp; &nbsp; &nbsp; &nbsp; document.querySelector('.nav-btn-container').classList.remove('active');&nbsp; &nbsp; }});此外,不应将您的放在<script src="script.js"></script>中head,而应该放在 的底部body
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5