[英]Getting Uncaught TypeError: Cannot read property 'offsetTop' of null error for scroll
I am having an issue where I get a uncaught type error, but the script still works.我遇到了一个问题,我收到了未捕获的类型错误,但脚本仍然有效。 I would like to resolve this but cannot seem to see the issue.
我想解决这个问题,但似乎看不到这个问题。 Any help is greatly appreciated!
任何帮助是极大的赞赏! Script is below.
脚本如下。
StickyNav: function() {
let mainNavLinks = document.querySelectorAll(".js-pdp-link");
let mainSections = document.querySelectorAll("section");
let lastId;
let cur = [];
window.addEventListener("scroll", event => {
let fromTop = window.scrollY + 70;
mainNavLinks.forEach(link => {
let section = document.querySelector(link.hash);
if (section.offsetTop <= fromTop && section.offsetTop + section.offsetHeight > fromTop) {
link.classList.add("js-active");
} else {
link.classList.remove("js-active");
}
});
});
}
When you do:当你这样做时:
let mainNavLinks = document.querySelectorAll(".js-pdp-link");
mainNavLinks.forEach(link => {
let section = document.querySelector(link.hash);
You are iterating all the elements with the .js-pdp-link
class and, if they implement the HTMLHyperlinkElementUtils interface ( ie is an a
or an area
element), extracting their hash property.您正在使用
.js-pdp-link
类迭代所有元素,如果它们实现了HTMLHyperlinkElementUtils接口(即a
或area
元素),则提取它们的哈希属性。 Then, you use the hash
as a selector.然后,您使用
hash
作为选择器。
It can fail in three different ways:它可能以三种不同的方式失败:
If the target element doesn't implement HTMLHyperlinkElementUtils
, link.hash
returns undefined
.如果目标元素未实现
HTMLHyperlinkElementUtils
,则link.hash
返回undefined
。
If the href
attribute contains no hash, link.hash
returns an empty string.如果
href
属性不包含哈希,则link.hash
返回一个空字符串。
If there is no element with a id
equal to that hash
, querySelector(link.hash)
is null
.如果没有
id
等于该hash
元素,则querySelector(link.hash)
为null
。
The case 2 results in SyntaxError: '' is not a valid selector
when you try document.querySelector(link.hash)
.当您尝试
document.querySelector(link.hash)
时,情况 2 会导致SyntaxError: '' is not a valid selector
。
The other two allow you to run the querySelector
but result in section
being null
.另外两个允许您运行
querySelector
但导致section
为null
。 Then, if you try to access its .offsetTop
property, you will get TypeError: section is null
.然后,如果您尝试访问其
.offsetTop
属性,您将得到TypeError: section is null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.