2

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

4 回答 4

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);
}
于 2011-04-13T19:07:35.147 回答
1

很简单:

/*@cc_on document.createStyleSheet("ie.css"); @*/
于 2011-04-13T19:15:57.787 回答
1

你知道Modernizr吗?

此外,在 HTML 开放标签中使用它也很棒(替换为no-jsjs

<!--[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") ){
}
于 2011-04-13T18:39:32.307 回答
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

于 2011-05-24T17:42:57.593 回答