使用< base>时,使锚链接指向当前页面 [英] Make anchor links refer to the current page when using <base>
问题描述
当我使用html < base>
标签为页面上的所有相关链接定义基本URL时,锚链接也直接指向基本URL。有没有一种方法来设置基本的URL,仍然允许锚链接引用当前打开的页面?
例如,如果我有一个页面在 http://example.com/foo/
:
目前的行为:
< base href =http://example.com//>
< a href =bar />酒吧< / a> <! - 指向http://example.com/bar/的链接 - >
< a href =#baz> baz< / a> <! - 指向http://example.com/#baz的链接 - >
期望的行为:
< base href =http://example.com//>
< a href =bar />酒吧< / a> <! - 指向http://example.com/bar/的链接 - >
< a href =#baz> baz< / a> <! - 指向http://example.com/foo/#baz的链接 - >
我在这个网站上找到了解决方案: using-base-href-with-anchors that does not需要jQuery,这里是一个工作片段:
< base href = https://example.com/\">< a href =/ test> / test< / a>< a href =javascript :; onclick =document.location.hash ='test';> Anchor< / a>
或不带内联js,如下所示:
document.addEventListener('DOMContentLoaded',function (){
var es = document.getElementsByTagName('a')
for(var i = 0; i< es.length; i ++){
es [i] .addEventListener('点击',函数(e){
e.preventDefault()
document.location.hash = e.target.getAttribute('href')
})
}
})
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?
For example, if I have a page at 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" -->
i found a solution on this site: using-base-href-with-anchors that doesn't require jQuery and here is a working snippet:
<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:
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')
})
}
})
这篇关于使用< base>时,使锚链接指向当前页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!