我正在创建一个允许深层链接的照片幻灯片。当用户浏览幻灯片时,URL 栏中的 anchor 标记也会更新,如果有人访问带有 anchor 标记的 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 anchor 更新时,这一切都会在浏览器的历史记录中注册,因此使用浏览器的后退按钮只需通过 anchor 返回。我希望发生的是后退按钮返回到最后加载的页面。
Imgur 具有我正在寻找的确切行为。这是一个真实的例子:
不过,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。
关于javascript - 使用URL anchor 深层链接相册,无需劫持后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11677874/