2017-12-24 37 views
0

사이드 바를 하위 탐색으로 사용하고 사용자 정의 javascript를 첨부하여 사용자가 섹션을 아래로 스크롤하는 동안 탐색 링크를 강조 표시합니다. 내 기본 js 파일에이 자바 스크립트가 포함되어 있습니다. 사이드 바는 모든 페이지에 포함되어 있지 않습니다. 성능 측면에서이 사이드 바에 첨부 된 스크롤 이벤트가 사이드 바가 포함되지 않은 사이트에서 발생하거나이 사이트에서 무시되는 스크립트 일 경우 알고 싶습니다.타겟팅 요소가없는 경우에도 스크롤 이벤트가 발생합니까?

 // waypoint for fixed sidebar 
     $('.tg-desktop__accordionWrapper').waypoint(function (direction) { 
      if (direction === 'down') { 
       $(this.element).addClass('tg-accordion__sidebar--fixed'); 
      } else { 
       $(this.element).removeClass('tg-accordion__sidebar--fixed'); 
      } 
     }); 

     // cache the navigation links 
     var $navigationLinks = $('.tg-accordion__sidebarLink'); 
     // cache (in reversed order) the sections 
     var $sections = $($(".tg-accordion__text").get().reverse()); 

     // map each section id to their corresponding navigation link 
     var sectionIdTonavigationLink = {}; 
     $sections.each(function() { 
      var id = $(this).attr('id'); 
      sectionIdTonavigationLink[id] = $('.tg-accordion__sidebarLink[href=#' + id + ']'); 
     }); 

     // throttle function, enforces a minimum time interval 
     function throttle(fn, interval) { 
      var lastCall, timeoutId; 
      return function() { 
       var now = new Date().getTime(); 
       if (lastCall && now < (lastCall + interval)) { 
        // if we are inside the interval we wait 
        clearTimeout(timeoutId); 
        timeoutId = setTimeout(function() { 
         lastCall = now; 
         fn.call(); 
        }, interval - (now - lastCall)); 
       } else { 
        // otherwise, we directly call the function 
        lastCall = now; 
        fn.call(); 
       } 
      }; 
     } 

     function highlightNavigation() { 
      // get the current vertical position of the scroll bar 
      var scrollPosition = $(window).scrollTop(); 

      // iterate the sections 
      $sections.each(function() { 
       var currentSection = $(this); 
       // get the position of the section 
       var sectionTop = currentSection.offset().top; 

       // if the user has scrolled over the top of the section 
       if (scrollPosition >= sectionTop) { 
        // get the section id 
        var id = currentSection.attr('id'); 
        // get the corresponding navigation link 
        var $navigationLink = sectionIdTonavigationLink[id]; 
        // if the link is not active 
        if (!$navigationLink.hasClass('active')) { 
         // remove .active class from all the links 
         $navigationLinks.removeClass('active'); 
         // add .active class to the current link 
         $navigationLink.addClass('active'); 
        } 
        // we have found our section, so we return false to exit the each loop 
        return false; 
       } 
      }); 
     } 

     $(window).scroll(throttle(highlightNavigation,100)); 

답변

0

기본적으로 스크롤 핸들러는 무조건 첨부되므로 예를 들어 사이드 바가 없어도 핸들러가 실행됩니다. 그리고, jQuery의 까다로운 특성으로 인해 아무 것도 던지지 않을 것입니다. 하지만 사이드 바가 없으면 원하는 부작용이 발생하지 않습니다.

사이드 바가없는 경우 스크롤 핸들러를 부착하지 않으면 매우 간단합니다. 실제로 해당 페이지 (또는 원하는 경우 "사이트")에는 질문의 코드가 필요하지 않은 것으로 보입니다. 이 같은

뭔가, 내가 기대 : 물론

var $navigationLinks = $('.tg-accordion__sidebarLink'); 

if($navigationLinks.length > 0) { 
    $('.tg-desktop__accordionWrapper').waypoint(function(direction) { 
     ... 
    }); 

    ... 
    ... 
    ... 

    function throttle(fn, interval) { 
     ... 
    } 

    function highlightNavigation() { 
     ... 
    } 

    $(window).scroll(throttle(highlightNavigation, 100)); 
} 

, 당신은 단일 페이지 응용 프로그램 (SPA)을했고, 일부 내용이 사이드 바 있었고, 일부는하지 않았다 경우,이 방법은 않을 것 작업. 당신은 스크롤 핸들러를 영구적으로 부착 된 채로 두거나 (경우에 따라 nada를 사용하는), 스크롤 핸들러가 컨텐츠와 함께 첨부/분리되도록 조정할 수 있습니다.

+0

감사합니다. 내 하루를 만들어, 기능에 대한 길이 옵션에 대해 생각하지 않았어! 스크롤 또는 크기 조정 처리기가 가끔씩 만 사용하는 경우 :-) 메리 크리스마스 @ Roamer-1888이 항상 수행되어야한다고 생각합니다. – DoUtDes