简体   繁体   中英

Is there a way to introduce Internet Explorer conditional comments using JavaScript?

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.

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

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") ){
}

很简单:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM