0

我正在创建一个允许深度链接的照片幻灯片。当用户浏览幻灯片时,URL 栏中的锚标记也会更新,如果有人访问带有锚标记的 URL,则首先显示该幻灯片。示例网址:

http://domain.com/news/some-article-slug/#/slide5

我通过简单地传递window.location.hash给对象来做到这一点:

start: window.location.hash.substring(7), // eg. "#/slide5"

// ...

var startingSlide;
this.start = 0;
this.deeplink = this.options.start != null;

if (this.deeplink) {
  startingSlide = Number(this.options.start);
  if (startingSlide > 0 && startingSlide <= this.total) {
    // use that number as the starting slide
  }
}

// ...

this.slides.bind("switch", function(idx) {
  if (_this.deeplink) {
    return window.location.hash = "/slide" + (idx + 1);
  }
});

这一切都很好。我的问题如下:

当用户查看幻灯片和 URL 锚点更新时,这一切都记录在浏览器的历史记录中,因此使用浏览器的后退按钮只是通过锚点返回。我希望后退按钮返回到最后加载的页面。

Imgur 具有我正在寻找的确切行为。这是一个真实的例子:

http://imgur.com/a/XCUET#0

不过,Imgur 的 javascript 都被缩小了,所以我无法通过阅读真正了解它是如何完成的。

谢谢!

更新

我最终使用了这样的东西:

var slidePath;

if (this.deeplink) {
  slidePath = [window.location.pathname, "/slide" + (idx + 1)].join("#");
  window.history.replaceState(null, window.title, slidePath);
}

我决定不使用 History.js 有几个原因——我试图在我的页面上不再包含任何 JS 库,当我尝试包含它时,它也给我带来了一些麻烦。对旧浏览器缺乏支持对我来说是可以的。

4

2 回答 2

2

您应该可以使用 history.js https://github.com/browserstate/History.js/ 查看他们的演示页面http://browserstate.github.com/history.js/demo/来完成它。

replaceState功能将满足您的需求。

history.js 也将模拟 HTML4 浏览器中的 replaceState 功能——包括 IE8 和 IE9。

于 2012-07-26T21:15:47.127 回答
1

您可以使用history.replaceState()来完成此操作。

this.slides.bind("switch", function(idx) {
  if (_this.deeplink) {
    var newUrl = window.location + "#/slide" + (idx + 1);
    return window.history.replaceState(null, window.title, newUrl);
  }
});
于 2012-07-26T21:11:41.330 回答