无法读取未定义链接的属性“顶部”href
问题描述:
我基于滚动导航中的链接的活动类。无法读取未定义链接的属性“顶部”href
function onScroll(event){
var scrollPosition = $(document).scrollTop();
$('.sticky-navigation-posts a').each(function() {
var currentLink = $(this);
var refElement = $(currentLink.attr("href"));
console.log(refElement);
if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
$('.sticky-navigation-posts .title-wrapper .post-title a').removeClass("active");
console.log('yes!');
currentLink.addClass("active");
} else {
currentLink.removeClass("active");
console.log('no!');
}
});
}
当我console.log(refElement)
,该元件被记录。但是,如果我console.log(refElement.position().top)
,则会引发此错误Cannot read property 'top' of undefined
。我一直在调试一段时间,但无法弄清楚。有任何想法吗?我也尝试在$()
中包装refElement
。
所有这些代码都包含在$(document).ready()
函数中。
答
好的我明白你的意思了。但是,它对我来说工作得很好。不知道你在哪里有问题?
我加了console.log(refElement.position().top);
,它正在正确地记录到控制台,甚至所需的行为正在工作!? http://jsfiddle.net/thesane/Dxtyu/3133/
你确定它是可见的吗? “jQuery不支持获取隐藏元素的位置坐标,也不支持在body元素上设置边框,边距或填充。”# – anolsi
元素位于页面上。未隐藏。 – Josh
可以肯定的,你可以做''的'console.log' refElement.is(':visible')' – anolsi