如何让IE支持html基本标签与相对href?喜欢:`<base href ="../"> </ base>`

Fre*_*ind 5 internet-explorer base relative-path

我根据规格知道,hrefbase应该是一个绝对URI.

href = uri [CT]
This attribute specifies an absolute URI that acts as the base URI for resolving relative URIs.
Run Code Online (Sandbox Code Playgroud)

但是firefox和chrome支持相对URI,例如../../,这对我当前的项目非常重要.对于我的项目,除了"relative base href"之外,我找不到更好的解决方案.

IE是否有任何黑客或工作场所让它支持相对URI?我的网页现在在firefox和chrome中运行良好,但它必须支持IE.

Che*_*ery 7

使用此函数将您的URL转换为绝对值:

function toAbsURL(s) { 
     var l = location, h, p, f, i; 
     if (/^\w+:/.test(s)) { 
       return s; 
     } 
     h = l.protocol + '//' + l.host + (l.port!=''?(':' + l.port):''); 
     if (s.indexOf('/') == 0) { 
       return h + s; 
     } 
     p = l.pathname.replace(/\/[^\/]*$/, ''); 
     f = s.match(/\.\.\//g); 
     if (f) { 
       s = s.substring(f.length * 3); 
       for (i = f.length; i--;) { 
         p = p.substring(0, p.lastIndexOf('/')); 
       } 
     } 
     return h + p + '/' + s; 
   }
Run Code Online (Sandbox Code Playgroud)

你可以用

var base = document.getElementsByTagName('base')[0];
base.href = toAbsURL(base.href);
Run Code Online (Sandbox Code Playgroud)

示例http://jsfiddle.net/tEpkx/1/

除了你必须检测浏览器,并且只为IE运行它.其他浏览器会base自动通过标记的href更新window.location ,此代码片段将再次更改它.所以把它写成

<!--[if IE]>
<script type="text/javascript">
var base = document.getElementsByTagName('base')[0];
base.href = toAbsURL(base.href);
</script>
<![endif]-->
Run Code Online (Sandbox Code Playgroud)

ps:<base />是单个标签,它不需要关闭标签.

更新以包括端口号(如果已设置).