JSF 2如何根据浏览器版本设置html样式

时间:2012-07-30 12:26:30

标签: html jsf jsf-2 conditional-comments omnifaces

我想在JSF 2应用程序中做的是根据浏览器版本设置正确的html样式,这里是示例代码:

<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]>    <html class="lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <!--<![endif]-->

如何在JSF 2中做到这一点?什么是最好/最简单的方法?

我在Omnifaces(o:conditionalComment)中发现了一些有趣的东西,但它只允许条件加载整个css,这对我来说是无用的......

3 个答案:

答案 0 :(得分:6)

<o:conditionalComment>不适用于CSS文件 。这是一种误解。从技术上讲,使用纯Facelets标签/组件实现您的要求是不可能的,因为它会导致格式错误的XML语法,从而导致Facelets编译错误。

<o:conditionalComment if="lt IE 7">
    <html lang="en" class="lt-ie9 lt-ie8 lt-ie7">
</o:conditionalComment>
<o:conditionalComment if="IE 7">
    <html lang="en" class="lt-ie9 lt-ie8">
</o:conditionalComment>
<o:conditionalComment if="IE 8">
    <html lang="en" class="lt-ie9">
</o:conditionalComment>
<o:conditionalComment if="gt IE 8">
    <h:outputText value="&lt;!--&gt;" escape="false" />
    <html lang="en" class="no-js">
    <h:outputText value="&lt;!--" escape="false" />
</o:conditionalComment>
...
</html>

这是 well formed XML。您知道,XML结束元素应与XML start元素在同一范围内。如果每个<html>在同一个父XML元素中都有自己的</html>,那么它将是有效的XML。但这反过来又不是有效的HTML。

在所有<h:outputText escape="false">代码上使用<html>即可。不要忘记对结束</html>标记执行相同操作。

<o:conditionalComment if="lt IE 7">
    <h:outputText value="&lt;html lang=&quot;en&quot; class=&quot;lt-ie9 lt-ie8 lt-ie7&quot;&gt;" escape="false" />
</o:conditionalComment>
<o:conditionalComment if="IE 7">
    <h:outputText value="&lt;html lang=&quot;en&quot; class=&quot;lt-ie9 lt-ie8&quot;&gt;" escape="false" />
</o:conditionalComment>
<o:conditionalComment if="IE 8">
    <h:outputText value="&lt;html lang=&quot;en&quot; class=&quot;lt-ie9&quot;&gt;" escape="false" />
</o:conditionalComment>
<o:conditionalComment if="gt IE 8">
    <h:outputText value="&lt;!--&gt;&lt;html lang=&quot;en&quot; class=&quot;no-js&quot;&gt;&lt;!--" escape="false" />
</o:conditionalComment>
...
<h:outputText value="&lt;/html&gt;" escape="false" />

非常尴尬,但HTML5 boilerplate(这种方法起源于此)本身也很尴尬,IMO。

或者,您可以考虑自己创建一个自定义<my:html>组件,生成所需的标记,以便您只需<my:html>...</my:html>即可。

答案 1 :(得分:3)

你可以使用相同的类制作3个CSS(每个浏览器一个)。您的HTML代码会更简单。

在标题中,您可以使用特定的浏览器css:

<h:outputStylesheet library="css" name="ie_7.css" rendered="#{header['User-Agent'].contains('; MSIE 7')}" />

答案 2 :(得分:2)

您不应有条件地声明<html>元素。

如果使用Chrome或Firefox的人想访问您的网站会怎样?

接受的做法是创建特定于IE版本的.css文件,并使用IE宏有条件地加载这些文件。

e.g

<link href="global_styles.css" rel="stylesheet" type="text/css"/>
<!--[if IE 7]-->
<link href="IE7_styles.css" rel="stylesheet" type="text/css"/>
<![endif]-->
<!--[if lte IE 6]-->
<link href="IE6_styles.css" rel="stylesheet" type="text/css"/>
<![endif]-->

在IE6_styles.css中,您可以向html类添加一些特定属性,也许* html黑客。这种方法的优点在于它可以在旧的IE浏览器中运行,但不会破坏现代浏览器。

BTW,这个例子来自David McFarland撰写的“CSS:失踪手册”。