如何使用 html、css 和 javascript 正确隐藏和显示导航菜单

How to properly Hide and Show navigation menu with html, css, and javascript

我正在努力做到当点击屏幕右上角的菜单图标时,导航菜单会在显示和隐藏之间切换。

这是上下文图片。

点击右上角的按钮时,根本不会在显示和隐藏之间切换。

这是目前为止的代码。

var menuBtn = document.getElementById("menuBtn")
var sideNav = document.getElementById("sideNav")
var menu = document.getElementById("menu")

menuBtn.onclick = function(){
    if(sideNav.style.right == "-250px"){
        sideNav.style.right = "0";
    }
    else{
        sideNav.style.right = "-250px";
    }
}
#sideNav{
    width: 250px; /*change font size of text in nav bar*/
    height: 100vh;
    position: fixed;
    right: 0;
    top:0;
    background: #009688;
    z-index: 2;
}
nav ul li{
    list-style: none;   
    margin: 45px 15px;
}
nav ul li a{
    text-decoration: none;
    color: #fff;
}
#menuBtn{
    width: 50px;
    height: 50px;
    background: #009688;
    text-align: center;
    position: fixed;
    right: 30px;
    top: 20px;
    border-radius: 3px;
    z-index: 3;
    cursor: pointer;
}
#menuBtn img{
    width: 20px;
    margin-top: 15px;
}
<div id="sideNav">
    <nav>
        <ul>
            <li><a href="#">HOME</a></li>
            <li><a href="#">COVID-19</a></li>
            <li><a href="#">SERVICES</a></li>
            <li><a href="#">REVIEWS</a></li>
            <li><a href="#">CONTACT</a></li>
        </ul>
    </nav>      
</div>
<div id="menuBtn">
    <img src="images/menu.PNG" id="menu">
</div>

您在 javascript 文件的第 2 行中有错字。 ...document.getElementById("sideNav ") 应该是 var sideNav = document.getElementById("sidNav")

var menuBtn = document.getElementById("menuBtn")
    var sideNav = document.getElementById("sidNav")
    var menu = document.getElementById("menu")
    
    menuBtn.onclick = function(){
        if(sideNav.style.right == "-250px"){
            sideNav.style.right = "0";
        }
        else{
            sideNav.style.right = "-250px";
        }
    }
#sidNav{
    width: 250px; /*change font size of text in nav bar*/
    height: 100vh;
    position: fixed;
    right: 0;
    top:0;
    background: #009688;
    z-index: 2;
}
nav ul li{
    list-style: none;   
    margin: 45px 15px;
}
nav ul li a{
    text-decoration: none;
    color: #fff;
}
#menuBtn{
    width: 50px;
    height: 50px;
    background: #009688;
    text-align: center;
    position: fixed;
    right: 30px;
    top: 20px;
    border-radius: 3px;
    z-index: 3;
    cursor: pointer;
}
#menuBtn img{
    width: 20px;
    margin-top: 15px;
}
<div id="sidNav">
        <nav>
            <ul>
                <li><a href="#">HOME</a></li>
                <li><a href="#">COVID-19</a></li>
                <li><a href="#">SERVICES</a></li>
                <li><a href="#">REVIEWS</a></li>
                <li><a href="#">CONTACT</a></li>
            </ul>
        </nav>      
    </div>
    <div id="menuBtn">
        <img src="images/menu.PNG" id="menu">
    </div>