无法读取未定义链接的属性“顶部”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()函数中。

+0

你确定它是可见的吗? “jQuery不支持获取隐藏元素的位置坐标,也不支持在body元素上设置边框,边距或填充。”# – anolsi

+0

元素位于页面上。未隐藏。 – Josh

+0

可以肯定的,你可以做''的'console.log' refElement.is(':visible')' – anolsi

好的我明白你的意思了。但是,它对我来说工作得很好。不知道你在哪里有问题?

我加了console.log(refElement.position().top);,它正在正确地记录到控制台,甚至所需的行为正在工作!? http://jsfiddle.net/thesane/Dxtyu/3133/

+0

我试过了。这个例子做了不同的处理。 http://jsfiddle.net/cse_tushar/Dxtyu/141/ – Josh

+0

好的,我不是在哪里得到你的例子,但我不认为'position()'方法可用于'attributes'。它只适用于'elements'或'tags'。如果你有小提琴,请给我演示 – Thesane

+0

jsfiddle.net/cse_tushar/Dxtyu/141 – Josh