最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove #Hash from url without refreshing. - Stack Overflow

programmeradmin5浏览0评论

I know there is many questions about this topic on Stackoveflow but i don't understand them.

So my question is how do i remove the #hash in the url (without refresh) after i pressed a link.

Here is one solution but i don't understand where i should put everything

My code is:

<a class="nav-link" href="#home">Home</a>

And #home is the id of the div i want to scroll to.

I know there is many questions about this topic on Stackoveflow but i don't understand them.

So my question is how do i remove the #hash in the url (without refresh) after i pressed a link.

Here is one solution but i don't understand where i should put everything

My code is:

<a class="nav-link" href="#home">Home</a>

And #home is the id of the div i want to scroll to.

Share Improve this question asked Jan 7, 2019 at 19:11 GnussonGnusson 11 silver badge3 bronze badges 6
  • 2 Hi Gnusson and wele to SO, can you post your code that you have tried so far? I'd be happy to help you work through the solution. – Josh Adams Commented Jan 7, 2019 at 19:13
  • Hi josh, i haven't tried any code ): I don't understand where i should put all the code from the example above.. Thanks for your help :D – Gnusson Commented Jan 7, 2019 at 19:14
  • If you're navigating to a section in that document you'll need to keep it in. Why do you want to remove it? – Andy Commented Jan 7, 2019 at 19:16
  • I think it looks ugly and i know it's possible to delete so thats why. – Gnusson Commented Jan 7, 2019 at 19:18
  • That's not a great reason to delete it. – Andy Commented Jan 7, 2019 at 19:19
 |  Show 1 more ment

3 Answers 3

Reset to default 4

If you want the hash link to function normally but just want the hash cosmetically erased, this code might be fine for you:

<!DOCTYPE html>
<html>

<a class="nav-link" href="#home" onClick="removehash()">Home</a>

<div style="height:3000px"></div>

<h1 id="home">HOME</h1>

<script>
    function removehash(){
        setTimeout(function(){
            history.replaceState("", document.title, window.location.pathname);
        }, 1);
    }
</script>

But the more correct way would probably be to attach a new event that controls the y-offset of the page. That's a bit trickier. Let me know if you're looking for that answer instead.

The easiest way would be replacing the hash with nothing.

location.hash = "";

But if done like this "example.#asdf" bees "example.#"


The less readable way, which also removes the '#' would be pushing a new state to the history.

history.pushState("", document.title, window.location.pathname);

This adds a new entry to the history, without the hash.

if you are using jquery so you can write this in your script file

$(document).ready(function(){
  $('.nav-link').click(function(e){ e.preventDefault(); })
})
发布评论

评论列表(0)

  1. 暂无评论