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

Chr*_*own 46 html href

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

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


目前的行为:

<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" -->
Run Code Online (Sandbox Code Playgroud)

期望的行为:

<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" -->
Run Code Online (Sandbox Code Playgroud)

dav*_*ubz 23

我在这个网站上找到了一个解决方案: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>
Run Code Online (Sandbox Code Playgroud)

或没有内联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')
    })
  }
})
Run Code Online (Sandbox Code Playgroud)

  • 使用内联javascript是完全有效的 - 它存在是有原因的.该文件中反对它的论点是虚假的.你应该将整个大型项目基于内联代码吗?可能不是.您是否可以使用有意图的内联代码并作为edge-case/gotchya的解决方案?绝对.出于某种原因,它是HTML规范的一部分.由于HTML文档的文件大小,对内联JS推行全面禁令是货币崇尚的废话.如果将相同的代码放在外部JS文件中,客户端仍会下载这些字节. (11认同)
  • 该解决方案不会很好地降级。在禁用 Javascript(或 [使用正则表达式的 html 解析器](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags))的浏览器上,您的链接将被破坏. (3认同)
  • 有很多原因导致为什么不好,其中一些解释[这里](http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a -坏事/) (2认同)

Jor*_*zem 11

基于@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);
    });
});
Run Code Online (Sandbox Code Playgroud)


Jam*_*ino 7

一点点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);
       }
    });
}
Run Code Online (Sandbox Code Playgroud)