如何使用 js 在 url 中隐藏#hash

How to hide # hash in a url using js

我有一个滚动插件,它使用我的 div ID 滚动到特定的锚点,

它正在像这样创建 urls:http://example.com/#examplediv|700

我想找到一种使用 js 或任何其他建议的方法来隐藏 url

中的散列的方法

我想将这个:http://example.com/#examplediv|700 转换成这个:http://example.com/

有什么想法吗?

散列在 location.hash 属性 中。只需将其设置为空字符串即可。如果您需要在其余代码中使用它,可以先将其保存在另一个变量中。

var saved_hash = location.hash;
location.hash = '';

您可以修改您正在使用的滚动插件,也可以自己在旁边添加它,但您需要这样做:

假设:与此滚动有关的所有 DIV 都需要具有 anchor-scrolls class.

HTML

<a href="#anchor-hash" class="anchor-scrolls">foo</a>

JS

//using jQuery
(function($){
   $('.anchor-scrolls').on('click', function(evt){
      evt.preventDefault(); //prevents hash from being append to the url
   });
)(window.jQuery);

您可以将其删除,保存并滚动到锚点,效果相同。

// Add smooth scrolling to links
$(".anchor-link").on('click', function(event) {

 // Prevent default anchor click behavior
 event.preventDefault();

 // Store hash
 var hash = this.hash;

 // Using jQuery's animate() method to add page scroll
 // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
 $('html, body').animate({
   scrollTop: $(hash).offset().top
 }, 800);

});

但仅适用于同一页面的锚点。如果锚点在不同的页面怎么办?