单击汉堡包图标时,粘性导航栏无法完全响应

Sticky Navigation bar not acting fully responsive when clicked on hamburger icon

我已经实现了让我的网页的导航栏具有粘性和半响应性,即在调整大小时它会变短但是当缩短时点击汉堡包图标会打开屏幕顶部的菜单(导航栏选项)它是最初定义的,而不是滚动屏幕的位置。

HTML代码:

<div class="topnav" id="myTopnav">
<a href="#home" class="active">Home</a>
<a href="#career">Careers</a>
<a href="#fellowship">Fellowship 2018</a>
<a href="javascript:void(0);" class="icon">
    <i class="fas fa-bars"></i>
</a>
</div>

CSS代码:

@media screen and (max-width: 600px){
.topnav.responsive{position: relative;}
.topnav.responsive .icon{
    position: absolute;
    right: 0;
    top: 0;
}
.topnav.responsive a{
    float: none;
    display: block;
    text-align: left;
}
}

JavaScript代码:

document.addEventListener('DOMContentLoaded',function(){

window.addEventListener('scroll', myFunctionForSticky);
var navbar = document.getElementById("myTopnav");
var sticky = navbar.offsetTop;

function myFunctionForSticky() {

    if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky");
    } else {
        navbar.classList.remove("sticky");
    }
}

  var icon = document.querySelector("a.icon");
  icon.addEventListener("click",function(){
    navbar.classList.toggle("responsive");
  })

})

要回答这个问题,你必须先了解CSS.

中'POSITIONING'的概念

TLDR; 如果你真的想让你的页眉在整个页面上保持粘性,你必须尝试 position: fixed

作为参考你可以看看这个pen

@media screen and (max-width: 600px){
    .topnav.responsive{position: fixed;}
    .topnav.responsive .icon{
        position: absolute;
        right: 0;
        top: 0;
    }
    .topnav.responsive a{
        float: none;
        display: block;
        text-align: left;
    }
}

这可能行得通,您可能还必须为菜单图标提供一个 z-index,以防它与列表项重叠。