2014-09-23 93 views
2

我在很多頁面上看到了以下代碼片段。據我所知,它用於根據不同的標識定位標籤進行平滑滾動。然而,我仍然對於正則表達式替換,thishash變量的工作方式有些困惑。JavaScript Smooth Scroll Explained

這個頻繁的代碼片段究竟在幹什麼?

$(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 2014-09-25 08:09:31

+0

嘿,這應該在2017年仍然有效嗎? – Elric 2017-09-16 00:29:16

+1

嗨@Elric,我沒有寫代碼,但是我確認它在2017年仍然有效。 – Jack 2017-09-21 05:59:03