【发布时间】:2022-08-17 16:50:21
【问题描述】:
(function ($) {
var window = $(window),
one = $(\"#one\"),
two = $(\"#two\"),
three = $(\"#three\"),
four = $(\"#four\"),
oneT = one.offset().top,
twoT = two.offset().top,
threeT = three.offset().top,
fourT = four.offset().top;
function Scroll(div) {
var tp = $(div).offset().top;
$(\"html, body\").animate({ scrollTop: tp }, 500);
}
var tmp = 0;
var mousewheelevt = /Firefox/i.test(navigator.userAgent)
? \"DOMMouseScroll\"
: \"mousewheel\";
$(\"section\").bind(mousewheelevt, function (e) {
var evt = window.event || e;
evt = evt.originalEvent ? evt.originalEvent : evt;
var delta = evt.detail ? evt.detail * -40 : evt.wheelDelta;
console.log(delta);
if (delta < 0) {
tmp++;
if (tmp > 0) {
var divT = $(this).next();
Scroll(divT);
tmp = 0;
}
} else if (delta > 0) {
tmp--;
console.log(\"going up\");
if (tmp < -1) {
var divT = $(this).prev();
Scroll(divT);
tmp = 0;
}
}
});
})(jQuery);
这是我使用的代码是否有任何问题,我收到错误调用
index.html:100 Uncaught TypeError: Cannot read properties of undefined (reading \'top\')
你能帮我解决这个问题吗?
-
请访问help center,使用tour 了解内容和How to Ask。如果您遇到困难,请发布您尝试的minimal reproducible example,并使用[<>] sn-p 编辑器记录输入和预期输出。
-
如果具有该 id 的元素不存在,
$(\"#id\").offset()将返回undefined(这会导致您的错误)。缩小您的哪个.top调用位于索引html 中的第100 行,这将告诉您在代码运行时哪个元素不存在。如果没有 HTML,我们将无法告诉您缺少什么。 -
这也很可能是这个代码:
var divT = $(this).next();Scroll(divT);(或 .prev()) - 当你到达最后,.next()将不返回任何元素(一个空的 jquery 集合)并且你不检查这个.