2011-12-13 38 views
4

我试图使我的网页无缝加载。如果你点击下面的一些链接的页面,你会看到我在说什么。无缝页面随AJAX更改

http://www.ultranoir.com/

http://www.itsmassive.com/

当你点击它加载的信息和/#链接

!/被添加到URL。如何添加此功能以便我的页面以同样的方式加载?有没有教程任何地方?

+2

查看[pjax](http://pjax.heroku.com/)或[History.js](https://github.com/balupton/History.js/)。 – 2011-12-13 19:58:17

回答

7

这被称为hashchange事件。您可以在#!之后更改值,而无需重新加载页面,然后您可以使用AJAX加载所需的信息。如果您使用的是支持HTML5的新浏览器,则可以使用History.pushState以类似的方式更改网址栏。

基本上,您将一个事件添加到链接,更改URL(使用location.hashpushState),然后您可以通过AJAX加载数据。

Here是一个体面的例子location.hash,and here's一个用于pushState

对于一个好的跨浏览器解决方案,我建议History.js

如果您想要使用History.js,在将脚本添加到页面后,您还需要添加一些JavaScript。

$('a.hash').click(function(e){ // For all links with the class "hash" 
    e.preventDefault(); // Don't follow link 
    History.pushState(null, '', this.href); // Change the current URL (notice the capital "H" in "History") 
    $('#content').slideUp('slow', function(){ // Animate it sliding up 
     var $this = $(this); 
     $this.load(this.href, function(){ // Use AJAX to load the page (or do whatever) 
      $this.slideUp('slow'); // Slide back down 
     }); 
}); 
+0

history.js看起来似乎是最好的选择。我从history.js的作者中发现了这个https://gist.github.com/854622,但对如何实现有点困惑。我包含了脚本,但不知道是否还有更多我需要做的事情。 。 – 2011-12-14 15:20:12