2011-10-23 29 views
1

我已經寫了這個簡單的插件,順利滾動瀏覽器窗口,並添加哈希鏈接到URL。jQuery的scrollTop如果URL有散列

$.fn.extend({ 
    scrollWindow: function(options) { 
     var defaults = { duration: "slow", easing : "swing" }     
     var options = $.extend(defaults, options); 
     return this.each(function() {    
      $(this).click(function(e) { 
       var target = $(this).attr('href'); 
       $('html,body').animate({scrollTop: $(target).offset().top}, options.duration, options.easing, function() { 
        location.hash = target; 
       }); 
       e.preventDefault(); 
      }); 

     }); 
    } 
}); 

如何擴展這個插件,使其自動向下滾動,如果它有存在於DOM中的URL散列網頁的部分?

我半知道如何通過使用window.location.hash這將工作,雖然我不清楚哪裏是最好的插件裏面添加這個。

回答

3

將函數存儲在一個單獨的變量中,如果存在散列,則調用該函數。我已實施您的請求,以便每次調用$().scrollWindow時都使用當前的location.hash。其他實現遵循相同的原則。

$.fn.extend({ 
    scrollWindow: function(options) { 
     var defaults = { duration: "slow", easing : "swing" }     
     var options = $.extend(defaults, options); 
     var goToHash = function(target){ 
      $('html,body').animate({scrollTop: $(target).offset().top}, options.duration, options.easing, function() { 
       location.hash = target; 
      }); 
     }; 
     if(location.hash.length > 1) goToHash(location.hash); 
     return this.each(function() {    
      $(this).click(function(e) { 
       //Remove junk before the hash if the hash exists: 
       var target = $(this).attr('href').replace('^([^#]+)#','#'); 
       goToHash(target); 
       e.preventDefault(); 
      }); 

     }); 
    } 
}); 
+0

哇絕對精彩謝謝。 –