制作固定导航栏,Uncaught TypeError?

Making a fixed navbar, Uncaught TypeError?

我正在制作一个固定的导航栏并使用 JavaScript 来检测用户何时在页面上滚动。

但是我遇到了一个问题,控制台告诉我 变量 navbarnull,在那之后,一旦我尝试向下滚动,它就会开始不断产生相同的错误:Uncaught TypeError: navbar is null

我真的不知道发生了什么,所以感谢任何帮助,干杯。

window.onscroll = function() {
  myFunction()
};

var navbar = document.getElementById("topNav");

var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky");
  } else {
    navbar.classList.remove("sticky");
  }
}
/*testing only*/

body {
  height: 500vh;
}

.topnav {
  background-color: #333;
  overflow: hidden;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%
}

.topnav a {
  float: left;
  color: #F72585;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav a.active {
  background-color: #F72585;
  color: white;
}

.topnav-right {
  float: right;
}
<div id="topNav" class="topnav">
  <a id="spaceStyle" class="active" href="#home" onclick="spaceChange()">SPACE</a>
  <a id="cyberStyle" href="#news" onclick="cyberChange()">CYBER-PUNK</a>
  <div class="topnav-right">
    <a id="creditsStyle" href="#about" onclick="credistsChange()">About</a>
  </div>
</div>

在页面完全加载后尝试访问您的元素。类似的东西:

    window.onscroll = function () { myFunction() };

    window.onload = function () {
        var navbar = document.getElementById("topNav");
        var sticky = navbar.offsetTop;

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