How to hide # hash in a url using js

。_饼干妹妹 提交于 2019-12-08 11:26:34

问题


I have a scroll plugin that uses my div ID to scroll to a specific anchor,

It's creating urls like this: http://example.com/#examplediv|700

I want to find a way using js or any other suggested method to hide the hash in the url

I want to transform this: http://example.com/#examplediv|700 into this: http://example.com/

Any ideas?


回答1:


You can either modify the scroll plugin you are using or add it yourself on the side but you will want to do something like this:

Assumption: All DIVs that you are concerned with regarding this scrolling will need to have the 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);



回答2:


The hash is in the location.hash property. Just set it to the empty string. If you need to use it in the rest of your code, you can save it in another variable first.

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



回答3:


You can remove it, save it and scroll to the anchor, which has the same effect.

// 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);

});

But works only for anchors at the same page. What if the anchor is at a different page?



来源:https://stackoverflow.com/questions/29001506/how-to-hide-hash-in-a-url-using-js

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