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

时间:2012-02-11 03:47:45

标签: internet-explorer relative-path base

我知道根据规范,href的{​​{1}}应该是绝对URI。

base

但是firefox和chrome支持相对URI,例如href = uri [CT] This attribute specifies an absolute URI that acts as the base URI for resolving relative URIs. ,这对我目前的项目非常重要。对于我的项目,我找不到比“relative base href”更好的解决方案。

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

1 个答案:

答案 0 :(得分:6)

使用此功能将您的网址转换为绝对网址:

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; 
   }

您可以使用

var base = document.getElementsByTagName('base')[0];
base.href = toAbsURL(base.href);

示例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]-->

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

已更新以包含端口号(如果已设置)。

相关问题