我有一段 HTML 代码,其中包含条件注释:
<!--[if IE]>
<link rel="stylesheet" ...>
<[endif]-->
此代码已经过测试,在初始页面呈现时包含在页面的 HEAD 部分时可以正常工作。
我想在 Ajax 响应中使用 JavaScript 将相同的条件 CSS 引入现有页面。
我试过:
var comment = document.createComment("[if IE]>\n<link rel=\"stylesheet\" ...>\n<[endif]");
Wicket.Head.addElement(comment); //this is framework code that just appends the element to the HEAD node of the page. I debugged and verified that it's doing the appendChild(...) call.
上述代码不会导致在 Internet Explorer 7 中应用样式表。有没有办法使用 JavaScript 以 Internet Explorer 理解的方式引入条件样式?
需要说明的是,我正在尝试使用 JavaScript 来创建条件样式,而不是尝试编写浏览器条件 JavaScript。
最佳答案
您可以在 innerHTML
中使用条件注释,如下所示:
var div = document.createElement("div");
div.innerHTML = "<!--[if IE]><i></i><![endif]-->";
if (div.getElementsByTagName("i").length) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = "ie_only.css";
document.getElementsByTagName("head")[0].appendChild(link);
}
关于javascript - 有没有办法使用 JavaScript 引入 Internet Explorer 条件注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5653788/