使用scrollspy更新地址栏window.location哈希 [英] Updating address bar window.location hash with scrollspy

查看:105
本文介绍了使用scrollspy更新地址栏window.location哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有scrollspy的菜单(使用twitter boostrap).当用户向下滚动到下一部分时,我想更新window.location.hash.

I've got a menu with scrollspy (using twitter boostrap). I want update the window.location.hash when the user scrolls down to a next section.

当用户向下滚动时,以下代码有效:

The following code works when the user scrolls down:

$(window).on('activate.bs.scrollspy', function (e) {
  location.hash = $("a[href^='#']", e.target).attr("href") || location.hash;
});

但是,当用户向上滚动时,它不能很好地工作.

However it does not work very well when the user scrolls upwards.

这样做的原因是,设置新的location.hash会触发浏览器导航到相应的锚点.这触发了连锁反应,用户将立即终止于页面顶部.

The reason for this is that setting a new location.hash triggers the browser to navigate towards that respective anchor. That triggers a chain reaction in which the user will instantly end up at the top of the page.

js-fiddle中的演示

现在解决该问题的最简单方法是什么?

Now what would be the simplest way to solve that problem?

推荐答案

可以使用HTML5历史记录更改URL的状态,而无需触发浏览器以遵循新状态. 并非所有浏览器都支持此功能.

It is possible to change the state of the URL with HTML5 history, without triggering the browser to follow the new state. This is not supported by all browsers.

使用history.replaceState()的另一个好处是,当用户使用浏览器的后退按钮时,它不仅会首先滚动.

Using history.replaceState() has the additional benefit that when the user uses the back button of the browser it will not just scroll up first.

$(window).on('activate.bs.scrollspy', function (e) {
    history.replaceState({}, "", $("a[href^='#']", e.target).attr("href"));
});

查看有效的js-fiddle .

这篇关于使用scrollspy更新地址栏window.location哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆