我认为阅读本文的人正在处理企业或遗留 Web 应用程序。
我们不能依赖 IE 条件注释,因为它可能会被 IE 忽略,信不信由你。至少,这是我坚持的案例。
我在脚本下方添加了与浏览器功能无关的脚本。
它在 IE11 中在 IE-5-7-8-9-10-11 渲染模式下使用 HTML5 <!DOCTYPE html> 进行了测试。
使用 IE 企业模式 和不使用。
它适用于像../MEDIA_FOLDER/ 这样的相对路径。
它适用于my_child_folder/MEDIA_FOLDER/,IE7-5 除外。
我有点懒得修复它并鼓励您使用根路径。
IE。只需使用/some_root_folder/my_child_folder/MEDIA_FOLDER/ 而不是my_child_folder/MEDIA_FOLDER/。 (或者改进我的脚本,或者不要使用 IE7-5。)
我们这里有两个主要错误和一堆案例。
首先,IE9 和 IE8 会自动将 href 属性中的路径值转换为 URL。他们这样做,就像所有现代浏览器一样。
但是 IE 页面没有看到这种自动更改。我们只是通过重新分配 href baseTag.href = baseTag.href 来解决这个问题。
其次,IE7-5 不会自动将路径值转换为 URL 值。我们应该手动完成。
还有其他情况会稍微改变 IE 的行为。这取决于
- 您使用什么 DOCTYPE。
- 如何呈现基本标签 -
<base/>、<base></base> 或 <base>。
- 您的 IE 企业模式 如何处理 IE 兼容性视图 设置。
例如,如果您将 IE Enterprise Mode 设置为 IE8 并设置了 Compatibility View,那么 IE 将设置 IE7 User-Agent HTTP 标头和 ASP.NET 表单将为 IE7 渲染。
或者 IE 条件注释 在弹出窗口、框架、iframe 或常见页面上将被忽略。这些都是我的真实案例。
(function () {
// Fixes old IE wrong behaiors of the href attribute of the base tag.
var preventIeHrefIgnoring = function (baseTag) {
var docMode = document.documentMode;
var isIe = docMode;
if (!isIe)
return;
if (docMode != 8 && docMode != 9)
return;
// IE8 and IE9 auto-convert path-like values of the href attribute, but do not apply it on the page.
// It is fixed by re-assining.
baseTag.href = baseTag.href;
}
var baseColl = document.getElementsByTagName('base');
if (!baseColl.length)
return;
var baseTag = baseColl[0];
var initialHref = baseTag.href;
if (!initialHref)
return;
var hrefIsUrl = initialHref.indexOf("https://") == 0 || initialHref.indexOf("http://") == 0;
if (hrefIsUrl) {
preventIeHrefIgnoring(baseTag);
return;
}
// Below we are dealing with IE7-5 only.
var targetHref = initialHref.indexOf('/') == 0 ? initialHref : "/" + initialHref;
var resultHref = window.location.protocol + "//" + window.location.host + targetHref;
baseTag.href = resultHref;
})();