有没有办法使用JavaScript引入Internet Explorer条件注释?

时间:2011-04-13 18:26:33

标签: javascript css dom wicket conditional-comments

我有一段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。

4 个答案:

答案 0 :(得分:5)

您可以在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);
}

答案 1 :(得分:1)

您知道Modernizr吗?

此外,在HTML开放代码中使用此内容非常棒(将no-js替换为js!)

<!--[if lt IE 7 ]><html lang=en-us class="no-js ie6"><![endif]--> 
<!--[if IE 7 ]><html lang=en-us class="no-js ie7"><![endif]--> 
<!--[if IE 8 ]><html lang=en-us class="no-js ie8"><![endif]--> 
<!--[if (gte IE 9)|!(IE)]><!--> <html lang=en-us class=no-js> <!--<![endif]--> 

所以你可以在CSS中做到这一点:

.ie7 .myDiv {
    foo:bar;
}

也可以通过javascript访问:

if( document.body.className.indexOf("ie") > -1 ){
     //
}

// or using jQuery

if( $(document.body).hasClass("ie6") ){
}

答案 2 :(得分:1)

很简单:

/*@cc_on document.createStyleSheet("ie.css"); @*/

答案 3 :(得分:0)

这一切都是不必要的。

public void renderHead(IHeaderResponse response) if(WebSession.get()。getClientInfo()。getClientProperties()。isBrowserInternetExplorer()){   response.renderJavaScriptReference(new JavaScriptResourceReference(MyClass.class,“ie.js”)); }

如果您选择使用Modernizr,请注意https://issues.apache.org/jira/browse/WICKET-3433