Змінити активний пункт меню на сторінці прокрутки?


95

Під час прокрутки сторінки активний пункт меню змінюється. Як це робиться?

Відповіді:


205

Це робиться шляхом прив’язки до події прокрутки контейнера (зазвичай вікна).

Швидкий приклад:

// 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
Якщо у вашому меню є поєднання ідентифікаторів на сторінці та звичайних сторінок, спочатку розмістіть посилання на ідентифікатор сторінки, а потім змініть menuItems = topMenu.find("a"),на menuItems = topMenu.find("a").slice(0,4),, замінивши 4на [ваші посилання на сторінку - 1].
Стівен Сосьє

5
Я насправді використовував menuItems = topMenu.find ('a [href ^ = "#"]'), таким чином повертаючи лише якірні посилання. Працює як шарм.
Джуліан К

1
Скрипка зламана. Не могли б ви це виправити? Thx
m1crdy

1
@ m1crdy Дякуємо за увагу. Це виправлено. Здається, щось у jQuery edge це зламало. Прекрасно працює з 2.1.0 :)
mekwall

1
@JoelAzevedo Здається, Sizzle змінився. Оновлено відповідь та тестовий приклад для роботи з jQuery 2.2.
mekwall

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 Коли користувач прокручує вміст праворуч, я хотів би активувати відповідне меню зліва та прокрутити меню, якщо потрібно, щоб показати активне меню. Будь-які вказівки вдячні.
Дікі Сінгх,

Це дуже бог, дякую. Однак я б змінив селектор атрибутів з * = на ^ =. Якщо ви використовуєте * =, тоді ви також вловите такі речі, як 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, якщо за цим ідентифікатором немає елемента. Не соромтеся вдосконалювати його ще більше;)

Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.