javascript - 使用URL anchor 深层链接相册,无需劫持后退按钮

标签 javascript html browser

我正在创建一个允许深层链接的照片幻灯片。当用户浏览幻灯片时,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 具有我正在寻找的确切行为。这是一个真实的例子:

/image/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。

关于javascript - 使用URL anchor 深层链接相册,无需劫持后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11677874/

相关文章:

javascript - 在 JavaScript 中如何修复元素显示和变量创建之间的初始差异

javascript - Fullcalendar Rails 上的 Popover Bootstrap

javascript - 延迟升级到 HTTPS (TLS/SSL)

javascript - 在 js 文件之外调用 JavaScript 函数

javascript - 为什么 navigator.mediaDevices 在本地主机和服务器中的工作方式不同?

javascript - jQuery $.post 导致浏览器堆栈溢出

javascript - 放大的弹出窗口在灯箱前面显示滚动条

javascript - React - 在下拉列表中过滤?

html - 如何访问 codeigniter 应用程序中文件夹内的 css 文件?

javascript - XHR 调用是宏任务还是微任务?