问题
I have a segment of HTML code which includes a conditional comment:
<!--[if IE]>
<link rel="stylesheet" ...>
<[endif]-->
This code was tested and works correctly when included in the HEAD section of the page, on the initial page rendering.
I would like to introduce the same conditional CSS to an existing page using JavaScript in an Ajax response.
I have tried:
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.
The above code does not cause the stylesheet to be applied in Internet Explorer 7. Is there a way, using JavaScript, to introduce the conditional style in a way that Internet Explorer understands?
Just to be clear, I am trying to use JavaScript to create a conditional style, not trying to write browser-conditional JavaScript.
回答1:
You can use conditional comments inside innerHTML
as follows:
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);
}
回答2:
Very simple:
/*@cc_on document.createStyleSheet("ie.css"); @*/
回答3:
Do you know Modernizr?
Also, it is great to use this in the HTML open tag (replace the no-js
with 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]-->
So you can do this in CSS:
.ie7 .myDiv {
foo:bar;
}
Can also be accessed in javascript with:
if( document.body.className.indexOf("ie") > -1 ){
//
}
// or using jQuery
if( $(document.body).hasClass("ie6") ){
}
回答4:
All this is unnecessary.
public void renderHead(IHeaderResponse response) if (WebSession.get().getClientInfo().getClientProperties().isBrowserInternetExplorer()) { response.renderJavaScriptReference(new JavaScriptResourceReference(MyClass.class, "ie.js")); }
If you choose to use Modernizr be aware of https://issues.apache.org/jira/browse/WICKET-3433
来源:https://stackoverflow.com/questions/5653788/is-there-a-way-to-introduce-internet-explorer-conditional-comments-using-javascr