未捕获的TypeError:无法读取null的属性'offsetTop'

时间:2018-09-27 08:22:16

标签: javascript html css html5 navigationbar

我正在使用HTML,CSS和JavaScript创建带有粘性和响应式导航栏的网页。我创建了响应式导航栏,并试图使其保持粘性。问题是它不粘滞并显示错误: 未捕获的TypeError:无法读取null的属性“ offsetTop”

HTML代码:

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

JavaScript代码:

// When the user scrolls the page, execute myFunction 
window.onscroll = function() {myFunctionForSticky()};

// Get the navbar
var navbar = document.getElementById("myTopnav");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. 
Remove "sticky" when you leave the scroll position
function myFunctionForSticky() {
    if(window.pageYOffset >= sticky){
    console.log("window.pageYOffset >= sticky");
}
else{
    console.log("Not window.pageYOffset >= sticky");
}
 if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky");
  } else {
    navbar.classList.remove("sticky");  
  }
}

/*Toggle between adding and removing the "responsive" class to topnav
when the user clicks on the icon*/

function myFunctionForResponsive() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}

如果我要上课而不是id,那么它会显示错误: 未被捕获的TypeError:无法读取未定义的属性“删除”

2 个答案:

答案 0 :(得分:2)

想要访问DOM的代码需要包装在监听DOMContentLoaded的事件监听器中。

当前,您正在尝试在浏览器尚未解析HTML时访问ID为myTopnav的元素,这意味着您的document.getElementById("myTopnav");返回null。在下一行代码中,您尝试读取offsetTop返回的null的{​​{1}}属性,结果为document.getElementById("myTopnav")

  

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

Cannot read property 'offsetTop' of null

答案 1 :(得分:0)

某些DOM元素没有此'offsetTop'属性,请在使用前检查其是否存在。  元素具有此属性