简体   繁体   中英

Menu with anchor link javascript or jquery

I found the jquery code with the anchor in the link.

jQuery (document) .ready (function () {
    jQuery ("a"). on ('click', function (event) {
        if (this.hash !== "") {
            event.preventDefault ();
            var hash = this.hash;
            jQuery ('html, body'). animate ({scrollTop: jQuery(hash).offset ().top}, 800, function () {
              window.location.hash = hash;
            });
        }
    });
});

My menu works on anchors as one page, but I have another link there which directs to an additional subpage from which after clicking the link with an anchor I had to use a slash / to return to a single page with anchor links. I would like that in the address bar of the page you can not see the anchor link only the main page address itself, but that the link would be directed to the appropriate part on the page with the anchor.

My menu:

<ul id = "categories" class="nav navbar-nav">
 <li><a href="/#anchor1">Anchor 1</a></li>
 <li><a href="/#anchor2">Anchor 2</a></li>
 <li><a href="/#anchor3">Anchor 3</a></li>
 <li><a href="new_page.html">New page</a></li>
</ul>

Address bar in the browser:

http://example.com/#anchor1

I would like to have the link moved to the anchor site after clicking on the anchor menu but hid the name of the anchor in the address:

http://example.com/

I am asking for help how to do it?

1.You need to remove this line:-

window.location.hash = hash;

From your code as it add the hash part to the URL.

Code need to be:-

<script>
jQuery (document) .ready (function () {
  jQuery ("a"). on ('click', function (event) {
    if (this.hash !== "") {
      event.preventDefault ();
      var hash = this.hash;
      jQuery('html, body').animate({scrollTop: jQuery(hash).offset ().top}, 800);
    }
  });
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM