在滚动时突出显示活动菜单项

我正在使用jQuery进行单页导航。 我想要的是当用户滚动时,突出显示的菜单将被更改。 我想出了以下代码:

HTML

   

Headline 1

Headline 2

Donec sed odio dui. Nulla vitae elit libero, a pharetra augue.
Nullam id dolor id nibh ultricies vehicula ut id elit.

Maurice Draait

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
Sed ut perspiciatis unde omnis iste natus error sit.

Agenda

Donec quis semper magna. Vivamus pellentesque tempor tincidunt.
Proin quis eros dolor. Donec sed venenatis enim.

Organisatie

Donec quis semper magna. Vivamus pellentesque tempor tincidunt.
Proin quis eros dolor. Donec sed venenatis enim.

Placehold

Headline 4

Donec quis semper magna.

Placehold

Headline 4

Donec quis semper magna.

Placehold

Headline 4

Donec quis semper magna.

Placehold

Headline 4

Donec quis semper magna.

JS

 // Update current item class function setActiveListElements(event){ var windowPos = $(window).scrollTop(); $('#primary-navwrapper li a[href^="#"]').each(function() { var currentLink = $(this); var refElement = $(currentLink.attr("href")); if (refElement.position()  windowPos) { $('#primary-navwrapper li a').removeClass("current"); currentLink.addClass("current"); } else{ currentLink.removeClass("current"); } }); } // Update menu item on scroll $(window).scroll(function() { // Call function setActiveListElements(); }); 

http://jsfiddle.net/8n06pvy9/6/

这段代码的问题是我收到了错误: Uncaught TypeError: Cannot read property 'top' of undefined

我还没有找到解决方案。

这是答案:

  // The id of the section we want to go to. var anchorId = $(this).attr("href"); // Our scroll target : the top position of the // section that has the id referenced by our href. if (anchorId.length > 1 && $(anchorId)) { var target = $(anchorId).offset().top - offset; } else { var target = 0; } 

当链接只有#时没有锚。 它指的是页面顶部,但没有附加锚元素。 因此,获得未定义的顶部是不可能的。 此代码现在检查href长度是否大于1(例如: #test )并且页面上有一个具有实际id的元素。 如果是,则计算偏移量,如果未将偏移量设置为0 。 这意味着,返回页面顶部。

http://jsfiddle.net/8n06pvy9/8/

实际上,相同类型的答案适用于突出问题。 它使用home导航按钮选择了文档,因为它没有链接到section元素。 jQuery不返回有效选择, position()将失败。

 function setActiveListElements(event){ var windowPos = $(window).scrollTop(); $('#primary-navwrapper li a[href^="#"]').each(function() { var currentLink = $(this); if ($(currentLink.attr("href")).length > 0) { var refElement = $(currentLink.attr("href")); if (refElement.position().top <= windowPos && (refElement.position().top + refElement.height() + $("#primary-navwrapper").height() ) > windowPos) { $('#primary-navwrapper li a').removeClass("current"); currentLink.addClass("current"); } else{ currentLink.removeClass("current"); } } }); } 

再次检查所选元素是否具有链接的section元素,如果是,则继续。

http://jsfiddle.net/8n06pvy9/9/