2013-06-03 36 views
3

所有内容都按原样运行,但是当jQuery到位时URL不会更改。无论如何,它有平滑滚动,并在同一时间更改网址?在此之前,我尝试了一种不同的方法,但它不像跨浏览器兼容。jQuery平滑滚动不会更改网址

我的HTML是:

<li class="representing-you-online"><a href="#representing-you-online">Representing you online</a></li> 
<li class="developing-your-people"><a href="#developing-your-people">Developing your people</a></li> 

我jQuery是:

$(document).ready(function() { 
     $('a[href^="#"]').click(function() { 
      var target = $(this.hash); 
      if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]'); 
      if (target.length == 0) target = $('html'); 
      $('html, body').animate({ scrollTop: target.offset().top }, 500); 
      return false; 
     }); 
    }); 
$(document).ready(function(){  
     $('#logo a').click(function() { 
      $('body,html').animate({ 
       scrollTop: 0 
      }, 800); 
      return false; 
     }); 
}); 

谢谢!

回答

1

更换点击处理代码为您的锚是这样的:

$(document).ready(function() { 
    $('a[href^="#"]').click(function() { 
     var target = $(this.hash); 
     var hash = this.hash; 
     if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]'); 
     if (target.length == 0) target = $('html'); 
     $('html, body').animate({ scrollTop: target.offset().top }, 500, function(){ 
      location.hash = hash; 
     }); 
     return false; 
    }); 
}); 

请注意,功能齐全的jQuery的.animate结束()。它改变了URL。

查看演示here