2017-09-07 1 views
0

현재 스크롤 위치가 일치하는 섹션에 있는지 여부에 따라 특정 탐색 링크를 강조 표시하는 jQuery 플러그인을 작성 중입니다.메뉴 강조 표시가있는 jQuery 인 페이지 탐색

지금 실행중인 방식대로 작동하며 원하는 모든 작업을 수행하고 있습니다. 피들보기 Demo Fiddle

해당 섹션 안에있을 때 링크가 올바르게 강조 표시됩니다. 또한 섹션 외부에있을 때 강조 표시를 제거하고 싶습니다.

는 나는 여기서 뭐 해요 : 내가 두 번째 섹션 내에서 아래로 스크롤있을 때

if (scrollPos + settings.offset >= currentSectionTop && scrollPos + settings.offset < currentSectionBottom) { 
    // Get the section ID and corresponding nav link. 
    var currentSectionID = $currentSection.attr('id'), 
     $correspondingNavLink = sectionMap[currentSectionID]; 

    // If the link isn't active already, make it so. 
    if (!$correspondingNavLink.hasClass('active')) { 
     $navLinks.removeClass('active'); 
     $correspondingNavLink.addClass('active'); 
     console.log('added active class'); 
    } 

    // Because this is the correct section, exit. 
     return false; 
} else { 
    if ($navLinks.hasClass('active')) { 
     $navLinks.removeClass('active'); 
     console.log('removed active class'); 
    }        
} 

문제가 온다. 이 경우 활성 클래스가 지속적으로 추가되고 제거되고 (콘솔 로그 확인) 이것이 정확하게 방지하려고 시도한 것입니다.

첫 번째 섹션 내부를 스크롤 할 때 이것이 발생하지 않는 것은 각 루프 내부에서 처음으로 검사되기 때문이며 일치하기 때문에 루프를 종료합니다.

결과가 정확히 원하는 경우에도 제거 - 추가 - 제거 - 추가 ... 사이클을 제거하여이 작은 최적화를 계속 만들고 싶습니다.

내가 어떻게 할 수 있습니까?

많은 감사를드립니다!

UPDATE :

JeyPack의 대답을 수행 한 후, 나는 내가 필요로 무엇을 얻었다. 섹션 밖에서 스크롤 할 때 활성 클래스를 제거하려면 섹션을 찾을 때 true로 변경되는 변수 만 사용했습니다. while 루프 이후에, 변수가 여전히 거짓이면 모든 섹션 밖에서 스크롤된다는 것을 의미하므로 활성 클래스가 적용되면 제거됩니다.

올바른 방향과 최적화를 위해 나를 안내해 준 JeyPack에게 감사드립니다. 당신이 더 예를 들어, while 루프를 사용한다

function highlightNav() { 
    // Get the current scroll position. 
    var currentSectionID, $correspondingNavLink, $currentSection, currentSectionTop, currentSectionBottom, 
     scrollPos = $w.scrollTop() + settings.offset, 
     i = $sections.length, 
     found = false; 

    // Loop through each section. 
    while (--i >= 0) { 
     // get current section 
     $currentSection = $sections.eq(i); 
     currentSectionTop = $currentSection.offset().top; 
     currentSectionBottom = $currentSection.offset().top + $currentSection.outerHeight(true); 

     // If we scrolled inside the section... 
     if (scrollPos >= currentSectionTop && scrollPos < currentSectionBottom) { 
      // Get the section ID and corresponding nav link. 
      currentSectionID = $currentSection.attr('id'); 
      $correspondingNavLink = sectionMap[currentSectionID]; 

      found = true; 
      // Because this is the correct section, break. 
      break; 
     } 
    } 

    if (!found && $navLinks.hasClass('active')) { 
     $navLinks.removeClass('active'); 
    } 

    // If the link isn't active already, make it so. 
    if ($correspondingNavLink && !$correspondingNavLink.hasClass('active')) { 
     $navLinks.removeClass('active'); 
     $correspondingNavLink.addClass('active'); 
     window.console.log('added active class', $correspondingNavLink); 
    } 
} 

답변

0

내부 'highlightNav'기능 : 여기

는 업데이트 된 코드입니다 그래서 당신은 $ currentSection을 검색 할 수 있고 $ correspondingNavLink를 얻을 수 있고, 루프를 벗어나 나중에 'active'클래스를 제거/추가 할 수 있습니다.

function highlightNav() { 
    // Get the current scroll position. 
    var currentSectionID, $currentSection, currentSectionTop, currentSectionBottom, 
     $correspondingNavLink = null, 
     scrollPos = $w.scrollTop() + settings.offset, 
     i = $sections.length; 

    // Loop through each section. 
    while (--i >= 0) { 
     // get current section 
     $currentSection = $sections.eq(i); 
     currentSectionTop = $currentSection.offset().top; 
     currentSectionBottom = $currentSection.offset().top + $currentSection.outerHeight(true); 

     // If we scrolled inside the section... 
     if (scrollPos >= currentSectionTop && scrollPos < currentSectionBottom) { 
      // Get the section ID and corresponding nav link. 
      currentSectionID = $currentSection.attr('id'); 
      $correspondingNavLink = sectionMap[currentSectionID]; 
      // Because this is the correct section, break. 
      state = 1; 
      break; 
     } 
    } 

    // If the link isn't active already, make it so. 
    if (state === 1) { 
     state = 0; 
     if (!$correspondingNavLink.hasClass('active')) { 
      $navLinks.removeClass('active'); 
      $correspondingNavLink.addClass('active'); 
      window.console.log('added active class', $correspondingNavLink); 
     } 
    } else if (state !== 2) { 
     state = 2; 
     $navLinks.removeClass('active'); 
     window.console.log('remove active class'); 
    } 
} 

내가 편집 당신의 바이올린을 가지고 https://jsfiddle.net/cwfqmv50/2/

+0

이 실제로 더 우아한, 그러나 추적하지 않아야 섹션 내에서 스크롤 할 때 이제 하이라이트가 제거되지 않습니다 ... 당신이 있습니까 어떤 주위에? –

+0

@Adi 나는 내 대답을 업데이트했다 : 요청한대로 작동 할 새로운 상태 인 var. – JeyPack