2012-03-17 37 views
0

我拿到這個劇本......jQuery的平滑滾動和URL字段

$(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); 
      location.hash = (this.hash); 
      return false; 
     } 
    } 
}); 
}); 

...但我與頁跳轉時,滾動到頂部的問題,但如果我拿出行.. 。

location.hash = (this.hash); 

它會正常工作,滾動都很好,但URL不會附加到被點擊的錨鏈接。

基本上我需要的URL顯示:http://www.example.com/#home < - 注意散列。

在此先感謝!

+0

我從來沒有得到它的工作,所以用另一個腳本去。 – Kia 2012-04-22 11:41:51

回答

0

使用回調.animate

$(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) { 
      var hash = this.hash; // 'this' will not be in scope in callback 
      $('html,body').animate({ scrollTop: target.offset().top }, 1000, function() { 
       location.hash = hash; 
      }); 
      return false; 
     } 
    } 
}); 
});