使用URL锚点深度链接相册,无需劫持后退按钮



我正在创建一个允许深度链接的照片幻灯片。当用户浏览幻灯片时,URL栏中的锚标签也会更新,如果有人访问带有锚标签的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锚点更新时,这一切都会在浏览器的历史记录中注册,因此使用浏览器的后退按钮只需返回锚点即可。我希望后退按钮返回到最后加载的页面。

伊姆古尔的行为正是我想要的。下面是一个真实的例子:

https://i.stack.imgur.com/Nu8aH.jpg

不过,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库,当我尝试包含它时,它也给我带来了一些麻烦。对旧浏览器缺乏支持对我来说是可以的。

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

replaceState函数将满足您的需要。

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

您可以使用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);
  }
});

最新更新