更改页面滚动上的活动菜单项?


95

向下滚动页面时,活动菜单项将更改。怎么做?

Answers:


206

通过绑定到容器的滚动事件(通常是窗口)来完成。

快速示例:

// Cache selectors
var topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   // Set/remove active class
   menuItems
     .parent().removeClass("active")
     .end().filter("[href='#"+id+"']").parent().addClass("active");
});​

请参阅jsFiddle上的上述操作,包括滚动动画。


2
如果菜单混合了页面ID和常规页面,请先放置页面ID链接,然后更改menuItems = topMenu.find("a"),menuItems = topMenu.find("a").slice(0,4),,替换4为[您的页面链接-1]。
Stephen Saucier

5
我实际上使用了menuItems = topMenu.find('a [href ^ =“#”]'),因此仅返回锚链接。奇迹般有效。
朱利安·K

1
小提琴坏了。你能解决吗?Thx
m1crdy 2014年

1
@ m1crdy感谢您的注意。已修复。似乎jQuery边缘中的某个东西破坏了它。在2.1.0下可以正常使用:)
mekwall

1
@JoelAzevedo似乎Sizzle已更改。更新了答案和测试用例以使用jQuery 2.2。
mekwall '16

16

只需检查我的代码和狙击和演示链接:

    // Basice Code keep it 
    $(document).ready(function () {
        $(document).on("scroll", onScroll);

        //smoothscroll
        $('a[href^="#"]').on('click', function (e) {
            e.preventDefault();
            $(document).off("scroll");

            $('a').each(function () {
                $(this).removeClass('active');
            })
            $(this).addClass('active');

            var target = this.hash,
                menu = target;
            $target = $(target);
            $('html, body').stop().animate({
                'scrollTop': $target.offset().top+2
            }, 500, 'swing', function () {
                window.location.hash = target;
                $(document).on("scroll", onScroll);
            });
        });
    });

// Use Your Class or ID For Selection 

    function onScroll(event){
        var scrollPos = $(document).scrollTop();
        $('#menu-center a').each(function () {
            var currLink = $(this);
            var refElement = $(currLink.attr("href"));
            if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
                $('#menu-center ul li a').removeClass("active");
                currLink.addClass("active");
            }
            else{
                currLink.removeClass("active");
            }
        });
    }

现场演示


3

只是为了补充@Marcus Ekwall的答案。这样做只会获得锚链接。如果锚链接和常规链接混在一起,也不会有问题。

jQuery(document).ready(function(jQuery) {            
            var topMenu = jQuery("#top-menu"),
                offset = 40,
                topMenuHeight = topMenu.outerHeight()+offset,
                // All list items
                menuItems =  topMenu.find('a[href*="#"]'),
                // Anchors corresponding to menu items
                scrollItems = menuItems.map(function(){
                  var href = jQuery(this).attr("href"),
                  id = href.substring(href.indexOf('#')),
                  item = jQuery(id);
                  //console.log(item)
                  if (item.length) { return item; }
                });

            // so we can get a fancy scroll animation
            menuItems.click(function(e){
              var href = jQuery(this).attr("href"),
                id = href.substring(href.indexOf('#'));
                  offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
              jQuery('html, body').stop().animate({ 
                  scrollTop: offsetTop
              }, 300);
              e.preventDefault();
            });

            // Bind to scroll
            jQuery(window).scroll(function(){
               // Get container scroll position
               var fromTop = jQuery(this).scrollTop()+topMenuHeight;

               // Get id of current scroll item
               var cur = scrollItems.map(function(){
                 if (jQuery(this).offset().top < fromTop)
                   return this;
               });

               // Get the id of the current element
               cur = cur[cur.length-1];
               var id = cur && cur.length ? cur[0].id : "";               

               menuItems.parent().removeClass("active");
               if(id){
                    menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
               }

            })
        })

基本上我取代了

menuItems = topMenu.find("a"),

通过

menuItems =  topMenu.find('a[href*="#"]'),

要在某处匹配所有具有锚点的链接,并更改所有必要的设置以使其与此一起工作

jsfiddle上看到它的实际效果


当菜单大于页面时,如何将其扩展到垂直菜单?pyze.com/product/docs/index.html当用户在右侧滚动内容时,我想在左侧激活适当的菜单,并在需要时滚动菜单以显示活动菜单。任何指针表示赞赏。
Dickey Singh'2

这是非常上帝,谢谢。但是,我会将属性选择器从* =更改为^ =。如果您使用* =,那么即使这是一个外部链接,也会捕获google.com/#something之类的内容。属性选择器在此处有很好的解释:w3schools.com/css/css_attribute_selectors.asp
雅克(Jacques)

0

如果您希望接受的答案在JQuery 3中起作用,请更改代码,如下所示:

var scrollItems = menuItems.map(function () {
    var id = $(this).attr("href");
    try {
        var item = $(id);
      if (item.length) {
        return item;
      }
    } catch {}
  });

我还添加了一个try-catch来防止javascript在该ID没有元素的情况下崩溃。随意改善它;)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.