2014-09-23 4 views
2

여러 페이지에서 다음 코드 스 니펫을 보았습니다. 다른 ID 앵커 태그에 따라 부드러운 스크롤에 사용된다는 것을 알고 있습니다. 그러나, 나는 조금/정규 표현식 대체, thishash 변수가 작동하는 방법에 대해 조금 혼란스러워합니다.JavaScript 스무스 스크롤 설명

이 빈번한 코드 스 니펫은 정확히 무엇을 수행합니까?

$(function() { 
     $('a[href*=#]:not([href=#])').click(function() { 
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) { 

       var target = $(this.hash); 
       target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); 
       if (target.length) { 
        $('html,body').animate({ 
         scrollTop: target.offset().top 
        }, 1000); 
        return false; 
       } 
      } 
     }); 
}); 

답변

6

코드에서 this은 클릭 한 링크를 나타냅니다. this.hash은 링크의 hash을 나타냅니다.

$(function() { 

    // Binding an event handler to all anchors that contain 
    // a hash (#), but not necessarily JUST a hash - like href="#" 
    // which is typically used in JS... 

    $('a[href*=#]:not([href=#])').click(function() { 

     // Two conditional checks 
     // First: 
     // location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
     // What we're doing is replacing the first forward slash (/) in the pathname 
     // for the current location and comparing it to the link that's been clicked. 
     // So http://personalsite.com/test/link/src, which normally would have 
     // a pathname of /test/link/src would be test/link/src 

     // The or check (||) is to see if the link matches the current domain 
     // location.hostname == this.hostname 

     // Basically, we want an internal anchor for the page we're on. 

     if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) { 

      // Assigning the variable target, with the hash of the link that's been clicked 
      // which is conveniently enough, a jquery selector for IDs (i.e. #hash) 
      var target = $(this.hash); 

      // We check the target length - basically, does the element exist? 
      // If length equals to 0, we query the DOM by name attribute. Otherwise, we just re-assign target to self. 
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); 

      // The rest is self explanatory... (animation using the target's offset) 
      // The return false prevents default behavior 

      if (target.length) { 
       $('html,body').animate({ 
        scrollTop: target.offset().top 
       }, 1000); 
       return false; 
      } 
     } 
    }); 
}); 

는 희망이 도움이 :

다음은 코드의 더 고장입니다!

+0

좋은 코드 분석. – Bowersbros

+0

이봐, 아직 2017 년에 작동해야합니까? – Elric

+1

안녕하세요 @ 엘릭, 코드를 작성하지 않았지만 여전히 2017 년에 작동하는지 확인했습니다. – Jack