制作固定导航栏,未捕获类型错误?

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


但我遇到了一个问题,控制台告诉我变量 navbar为null,之后,只要我尝试向下滚动,它就会开始不断生成相同的错误: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>


翻过高山走不出你
浏览 75回答 1
1回答

MM们

页面完全加载后尝试访问您的元素。像这样的东西:&nbsp; &nbsp; window.onscroll = function () { myFunction() };&nbsp; &nbsp; window.onload = function () {&nbsp; &nbsp; &nbsp; &nbsp; var navbar = document.getElementById("topNav");&nbsp; &nbsp; &nbsp; &nbsp; var sticky = navbar.offsetTop;&nbsp; &nbsp; &nbsp; &nbsp; function myFunction() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (window.pageYOffset >= sticky) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; navbar.classList.add("sticky");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; navbar.classList.remove("sticky");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript