Make anchor links refer to the current page when using <base>

后端 未结 12 1178
情书的邮戳
情书的邮戳 2020-11-30 03:29

When I use the html tag to define a base URL for all relative links on a page, anchor links also refer directly to the base URL. Is there a way to

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 04:25

    My approach is to search for all links to an anchor, and prefix them with the document URL.

    This only requires javascript on the initial page load and preserves browser features like opening links in a new tab. It also and doesn't depend on jQuery/etc.

    document.addEventListener('DOMContentLoaded', function() {
      // get the current URL, removing any fragment
      var documentUrl = document.location.href.replace(/#.*$/, '')
    
      // iterate through all links
      var linkEls = document.getElementsByTagName('A')
      for (var linkIndex = 0; linkIndex < linkEls.length; linkIndex++) {
        var linkEl = linkEls[linkIndex]
      
        // ignore links that don't begin with #
        if (!linkEl.getAttribute('href').match(/^#/)) {
          continue;
        }
      
        // convert to an absolute url
        linkEl.setAttribute('href', documentUrl + linkEl.getAttribute('href'))
      }
    
    })
    

提交回复
热议问题