Updating address bar window.location hash with scrollspy

荒凉一梦 提交于 2019-12-21 21:46:35

问题


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.

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.

Demo in js-fiddle

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


回答1:


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.

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"));
});

See working js-fiddle.




回答2:


For more cross-browser hash update you can use this JS:

$(window).on('activate.bs.scrollspy', function(e) {
  var $hash, $node;
  $hash = $("a[href^='#']", e.target).attr("href").replace(/^#/, '');
  $node = $('#' + $hash);
  if ($node.length) {
    $node.attr('id', '');
  }
  document.location.hash = $hash;
  if ($node.length) {
    return $node.attr('id', $hash);
  }
});

It removes temporarily the searched hash than adds it via the window.location and then restores hash in question. Unfortunately I don't know the exact compatibility range for this solution but IE9 is supported for sure and probably all older versions on IE as well (I don't care about older browsers in my projects so I didn't test this solution).




回答3:


I use this for Bootstrap v4:

$(window).on('activate.bs.scrollspy', function(e) {
    history.replaceState({}, "", $('.nav-item .active').attr("href"));
});


来源:https://stackoverflow.com/questions/23070777/updating-address-bar-window-location-hash-with-scrollspy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!