Липкая навигация, неправильно добавляющая активные ссылки - PullRequest
0 голосов
/ 26 сентября 2018

Я пытаюсь реализовать навигацию.Я использовал этот код , чтобы сделать то же самое.

<nav>
<ul id="mainNav">
    <li class="active"><a href="#home">Home</a></li>
    <li><a href="#work">Work</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#contact">Contact</a></li>    
  </ul>
</nav>
<section id="home"><h2>Home</h2></section>
<section id="work" data-sr><h2>Work</h2></section>
<section id="about"><h2>About</h2></section>
<section id="contact"><h2>Contact</h2></section>

// Cache selectors

var lastId,
 topMenu = $("#mainNav"),
 topMenuHeight = topMenu.outerHeight()+1,
 // 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 click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
  var href = $(this).attr("href"),
      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
  $('html, body').stop().animate({ 
      scrollTop: offsetTop
  }, 850);
  e.preventDefault();
});
$(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 : "";

   if (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("active")
         .end().filter("[href=#"+id+"]").parent().addClass("active");
   }                   
});

Требование: - Я хочу, чтобы навигация содержала ссылки, которые можно поменять местами согласно требованию.

Проблема: - В приведенном выше коде, когда я меняю ссылки, он не добавляет активные классы должным образом.Если я поменяю местами навигационные ссылки И ссылку на раздел, то только тогда она будет работать хорошо.Например, если в моей навигации есть ДОМОЙ, РАБОТА, ОБ и КОНТАКТ.Тогда я смогу поменять местами рабочую ссылку со ссылкой на контакт, и все же моя липкая навигация ДОЛЖНА правильно добавлять активные классы, БЕЗ смещения их соответствующих разделов.

Пожалуйста, помогите мне достичь описанного выше сценария.

1 Ответ

0 голосов
/ 26 сентября 2018

Приведенный ниже код должен решить вашу проблему.

// Cache selectors
var lastId,
 topMenu = $("#mainNav"),
 topMenuHeight = topMenu.outerHeight()+1,
 // All list items
 menuItems = topMenu.find("a"),
 // Anchors corresponding to menu items
 scrollItems = $('section');

// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
  var href = $(this).attr("href"),
      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
  $('html, body').stop().animate({ 
      scrollTop: offsetTop
  }, 850);
  e.preventDefault();
  setActiveNav(href);
});

function setActiveNav(href) {
  menuItems.each((index, menu) => {
    if(menu.hash === href) {
      $(menu).parent().addClass('active');
    } else {
      $(menu).parent().removeClass('active');
    }
  });
}

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


   // Get id of current scroll item
   var cur = scrollItems.toArray().findIndex(item => {
    return (item.offsetTop >= fromTop);
});
   // Get the id of the current element
   var id = cur && cur > -1 ? scrollItems[cur].id : "";

   if (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("active")
         .end().filter("[href=#"+id+"]").parent().addClass("active");
   }
});

Структурирование ваших функций в отдельных функциях решит будущие накладные расходы на обслуживание.

В основном проблемы связаны со структурированием, индексом элемента и положением.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...