Browser back button does not work for Anchor links

后端 未结 4 2524
广开言路
广开言路 2021-02-20 08:36

In the footer of my page there a few links that point to different sections on the same page using anchor tags (# appended to the URL of the page).

This works fine, just

4条回答
  •  囚心锁ツ
    2021-02-20 09:16

    http://www.the-art-of-web.com/javascript/remove-anchor-links/

    Visit that site. Scroll to the bottom and use test the anchors. It's doing what you want.

    "The following code will parse your HTML page and override the function of any links that target anchor points on the same page. The link function will be replaced with a call to the scrollIntoView method of the target element:

    document.addEventListener("DOMContentLoaded", function() {
      var links = document.getElementsByTagName("A");
      for(var i=0; i < links.length; i++) {
        if(!links[i].hash) continue;
        if(links[i].origin + links[i].pathname != self.location.href) continue;
        (function(anchorPoint) {
          links[i].addEventListener("click", function(e) {
            anchorPoint.scrollIntoView(true);
            e.preventDefault();
          }, false);
        })(document.getElementById(links[i].hash.replace(/#/, "")));
      }
    }, false);
    

提交回复
热议问题