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

后端 未结 12 1126
情书的邮戳
情书的邮戳 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 03:58

    From the example given in the question. To achieve desired behavior, I do not see the need of using "base" tag at all.

    The page is at http://example.com/foo/

    Below code will give the desired behaviour:

    <a href="/bar/">bar</a> <!-- Links to "http://example.com/bar/" -->
    <a href="#baz">baz</a> <!-- Links to "http://example.com/foo/#baz" -->
    

    The trick is to use "/" at the beginning of string href="/bar/".

    0 讨论(0)
  • 2020-11-30 04:02

    To prevent multiple # in URL:

             document.addEventListener("click", function(event) {
              var element = event.target;
              if (element.tagName.toLowerCase() == "a" && 
                element.getAttribute("href").indexOf("#") === 0) {
                my_href = location.href + element.getAttribute("href");
                my_href = my_href.replace(/#+/g, '#');
                element.href = my_href;
              }
            });
    
    0 讨论(0)
  • 2020-11-30 04:04

    A little bit of jQuery could probably help you with that. Although base href is working as desired, if you want your links beginning with an anchor (#) to be totally relative, you could hijack all links, check the href property for those starting with #, and rebuild them using the current URL.

    $(document).ready(function () {
        var pathname = window.location.href;
        $('a').each(function () {
           var link = $(this).attr('href');
           if (link.substr(0,1) == "#") {
               $(this).attr('href', pathname + link);
           }
        });
    }
    
    0 讨论(0)
  • 2020-11-30 04:04

    If you use PHP, you can use following function to generate anchor links:

    function generateAnchorLink($anchor) {
      $currentURL = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
      $escaped = htmlspecialchars($currentURL, ENT_QUOTES, 'UTF-8');
      return $escaped . '#' . $anchor;
    }
    

    Use it in the code like that:

    <a href="<?php echo generateAnchorLink("baz"); ?>">baz</a>
    
    0 讨论(0)
  • 2020-11-30 04:09

    Here's an even shorter, jQuery based version I use in a production environment, and it works well for me.

    $().ready(function() {
      $("a[href^='\#']").each(function(){ 
        this.href=location.href.split("#")[0]+'#'+this.href.substr(this.href.indexOf('#')+1);
      });
    });
    
    0 讨论(0)
  • 2020-11-30 04:11

    You could also provide an absolute url:

    <base href="https://example.com/">
    <a href="/test#test">test</a>
    

    Rather than this

    <a href="#test">test</a>
    
    0 讨论(0)
提交回复
热议问题