Html 使用 <base> 时使锚链接指向当前页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8108836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:28:39  来源:igfitidea点击:

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

htmlhref

提问by Chris Down

When I use the html <base>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 set the base URL that would still allow anchor links to refer to the currently open page?

当我使用 html<base>标记为页面上的所有相关链接定义基本 URL 时,锚链接也直接引用基本 URL。有没有办法设置仍然允许锚链接引用当前打开页面的基本 URL?

For example, if I have a page at http://example.com/foo/:

例如,如果我有一个页面http://example.com/foo/



Current behaviour:

当前行为:

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

Desired behaviour:

期望的行为:

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

回答by davide bubz

i found a solution on this site: using-base-href-with-anchorsthat doesn't require jQuery and here is a working snippet:

我在这个网站上找到了一个解决方案:using-base-href-with-anchors不需要 jQuery,这里是一个工作片段:

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

<a href="/test">/test</a>
<a href="javascript:;" onclick="document.location.hash='test';">Anchor</a>

or without inline js, something like this:

或者没有内联js,像这样:

document.addEventListener('DOMContentLoaded', function(){
  var es = document.getElementsByTagName('a')
  for(var i=0; i<es.length; i++){
    es[i].addEventListener('click', function(e) {
      e.preventDefault()
      document.location.hash = e.target.getAttribute('href')
    })
  }
})

回答by Joram van den Boezem

Building upon @James Tomasino answer, this one is slightly more efficient, solves a bug with double hashes in the url and a syntax error.

以@James Tomasino 的回答为基础,这个答案稍微高效一些,解决了 url 中存在双哈希和语法错误的错误。

$(document).ready(function() {
    var pathname = window.location.href.split('#')[0];
    $('a[href^="#"]').each(function() {
        var $this = $(this),
            link = $this.attr('href');
        $this.attr('href', pathname + link);
    });
});

回答by James Tomasino

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 hiHyman all links, check the href property for those starting with #, and rebuild them using the current URL.

一点点 jQuery 可能会帮助你。尽管 base href 可以正常工作,但如果您希望以锚点 (#) 开头的链接完全相关,则可以劫持所有链接,检查以 # 开头的链接的 href 属性,并使用当前 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);
       }
    });
}

回答by contendia

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

这是我在生产环境中使用的一个更短的基于 jQuery 的版本,它对我来说效果很好。

$().ready(function() {
  $("a[href^='\#']").each(function(){ 
    this.href=location.href.split("#")[0]+'#'+this.href.substr(this.href.indexOf('#')+1);
  });
});

回答by Micha? Per?akowski

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

如果你使用 PHP,你可以使用以下函数来生成锚链接:

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>

回答by Yektaweb Company

To prevent multiple # in URL:

要防止 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;
          }
        });

回答by Micha? Per?akowski

I'm afraid there is no way to solve this without any server-side or browser-side script. You can try the following plain JavaScript (without jQuery) implementation:

恐怕没有任何服务器端或浏览器端脚本就无法解决这个问题。您可以尝试以下纯 JavaScript(无 jQuery)实现:

document.addEventListener("click", function(event) {
  var element = event.target;
  if (element.tagName.toLowerCase() == "a" && 
      element.getAttribute("href").indexOf("#") === 0) {
    element.href = location.href + element.getAttribute("href");
  }
});
<base href="https://example.com/">

<a href="/test">/test</a>
<a href="#test">#test</a>

It also works (unlike the other answers) for dynamically generated (i.e. created with JavaScript) aelements.

它也适用于动态生成(即使用 JavaScript 创建)a元素(与其他答案不同)。

回答by atoms

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>

回答by Steve Kang

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

从问题中给出的例子来看。为了实现所需的行为,我认为根本不需要使用“base”标签。

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

该页面位于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/".

诀窍是在字符串 href="/bar/" 的开头使用 "/"。

回答by OuzoPower

You can use some javascript code inside the tag that links.

您可以在链接的标签内使用一些 javascript 代码。

<span onclick="javascript:var mytarget=((document.location.href.indexOf('#')==-1)? document.location.href + '#destination_anchor' : document.location.href);document.location.href=mytarget;return false;" style="display:inline-block;border:1px solid;border-radius:0.3rem"
 >Text of link</span>

How does it work when the user clicks?

当用户点击时它是如何工作的?

  1. First it checks if the anchor (#) is already present in the URL. The condition is tested before the "?" sign. This is to avoid the anchor being added twice in the URL if the user clicks again the same link, since the redirection then wouldn't work.
  2. If there is sharp sign (#) in the existing URL, the anchor is appended to it and the result is saved in the mytargetvariable. Else, keep the page URL unchanged.
  3. Lastly, go to the (modified or unchanged) URL stored by the mytargetvariable.
  1. 首先,它检查 URL 中是否已经存在锚 (#)。在“?”之前测试条件。标志。这是为了避免在用户再次单击同一链接时在 URL 中添加两次锚点,因为重定向将不起作用。
  2. 如果现有 URL 中存在尖号 (#),则将锚附加到它并将结果保存在mytarget变量中。否则,保持页面 URL 不变。
  3. 最后,转到mytarget变量存储的(已修改或未更改的)URL 。

Instead of <span>, you can also use <div>or even <a>tags. I would suggest avoiding <a>in order to avoid any unwanted redirection if javascript is disabled or not working, and emultate the look of your <a>tag with some CSS styling. If despite this you want to use the <a>tag, don't forget adding return false;at the end of the javascript and set the href attribute like this <a onclick="here the javascript;return false;" href="javascript:return false;">...</a>.

除了 <span>,您还可以使用<div>甚至<a>标签。<a>如果 javascript 被禁用或不起作用,我建议避免以避免任何不需要的重定向,并<a>使用一些 CSS 样式模拟标签的外观。尽管如此,如果您想使用该<a>标签,请不要忘记return false;在 javascript 末尾添加并像这样设置 href 属性<a onclick="here the javascript;return false;" href="javascript:return false;">...</a>