我用 jQuery 构建了这个非常基本的 .map() 函数,以将我的 HTML 部分的顶部偏移量存储在一个数组中(在正文末尾的脚本标记内):
jQuery
$(window).load(function() {
var obj = $(this),
sec = $('section'),
arr = sec.map(function() {
return obj.offset().top
}).get();
})
它几乎和jQuery 文档中的一样简单。它已经奏效了!...直到一周前。
我的 HTML(jade [使用 CodeKit 编译])具有非常简单的结构:
HTML
body.preload
section#id1
whateverContent
section#id2
moreContent
section#id3
evenMoreContent
...
令人惊讶的是,今天控制台决定告诉我 top 是未定义的:
安慰
Uncaught TypeError: Cannot read property 'top' of undefined
假设在我的函数中 .map() 采用所有部分标记并返回每个迭代元素的偏移量,正如文档中所述:
在回调函数中, this 指的是每次迭代的当前 DOM 元素。
更不用说大约一周前这对我来说已经很有效了。
那么这里有什么问题呢?
有错别字吗?中间有什么东西在捣乱吗?我在那里定义了更多变量,但它不应该有任何区别,不是吗?莫非跟编玉有关系?使用 CodeKit?任何线索都非常感谢!
这是我在页面上未经审查的完整 JS(一周前工作):
// Let DOM finish loading
$(window).load(function() {
// CSS animation hack
$('body').removeClass('preload')
// Sticky nav and active class
var win = $(window),
doc = $(document),
obj = $(this),
sec = $('section'),
nav = $('nav'),
anc = $('nav a'),
pos = nav.offset().top,
// Fill array with top offsets from sections
arr = sec.map(function() {
return obj.offset().top
}).get(),
act = function() {
win.scrollTop() > pos ? nav.addClass('sticky')
: nav.removeClass('sticky'),
$.each(arr, function(i, val) {
(win.scrollTop() > val && win.scrollTop() < (val + sec.eq(i).outerHeight(true) + 1) ) ? anc.eq(i).addClass('active')
: anc.eq(i).removeClass('active')
})
};
// Execute sticky function
win.scroll(act)