当我使用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" -->
期望的行为:
<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" -->
如果你正在使用Angular 2+(并且只是定位网络),你可以这样做:
component.ts
document = document; // Make document available in template
component.html
<a [href]="document.location.pathname + '#' + anchorName">Click Here</a>
基于@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);
});
});
一点点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);
}
});
}
这是我在生产环境中使用的更短的,基于jQuery的版本,它对我很有用。
$().ready(function() {
$("a[href^='\#']").each(function(){
this.href=location.href.split("#")[0]+'#'+this.href.substr(this.href.indexOf('#')+1);
});
});
如果使用PHP,则可以使用以下函数生成锚链接:
function generateAnchorLink($anchor) {
$currentURL = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$escaped = htmlspecialchars($currentURL, ENT_QUOTES, 'UTF-8');
return $escaped . '#' . $anchor;
}
在代码中使用它:
<a href="<?php echo generateAnchorLink("baz"); ?>">baz</a>
我担心没有任何服务器端或浏览器端脚本就无法解决这个问题。您可以尝试以下纯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>
它也可以(与其他答案不同)动态生成(即使用JavaScript创建)a
元素。
要防止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;
}
});
您还可以提供绝对网址:
<base href="https://example.com/">
<a href="/test#test">test</a>
而不是这个
<a href="#test">test</a>
从问题中给出的例子。为了达到理想的行为,我认为根本不需要使用“base”标签。
下面的代码将给出所需的行为:
<a href="/bar/">bar</a> <!-- Links to "http://example.com/bar/" -->
<a href="#baz">baz</a> <!-- Links to "http://example.com/foo/#baz" -->
诀窍是在字符串href =“/ bar /”的开头使用“/”。