【问题标题】:How to conditionally load CSS如何有条件地加载 CSS
【发布时间】:2014-05-03 23:31:30
【问题描述】:

下面的代码定义了浏览器是否不是IE执行的:

<!--[if !IE]> -->
...
<!-- <![endif]-->

如果我想编辑以上内容以...

IF IE but IE version is less than 9 .. SHOW THIS
ELSE IF IE version is greater than or equal to 9 OR Other Browser .. SHOW THIS

我怎样才能实现它?在搜索时,我发现的只是如何确定它是 IE 版本还是根本不是 IE。

【问题讨论】:

  • 我相信您已经阅读过,条件 cmets 仅适用于 IE。一般来说,我所做的是先加载常见情况,然后使用条件 cmets 加载 IE 版本特定的 CSS。
  • 这些被称为 条件 cmets,并在网络上广泛记录。
  • 另外,IE 10 不支持条件 cmets。

标签: html css internet-explorer cross-browser


【解决方案1】:

你可以这样使用:

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

然后通过以下方式定位您的选择器:

 .ie8 .your-selector

here所述。

如果你想有一个开关,你也可以在一个类中切换到 html-tag,例如

<!--[if gt IE 8]><!--> <html class ="i-am-so-happy-it-is-no-ancient-ie"><!--<![endif]-->

并像这样使用它:

.i-am-so-happy-it-is-no-ancient-ie .your-selector{...}
.ie6 .your-selector {...}

编辑 我忘记了 IE 9 .. Acutally Paul Irish 建议使用这种形式(我稍作调整以使用单个 .ie .class 使非 ie-switch 成为可能 - 尽管您必须知道 ie 6 不支持多个类,但你明白了):

<!--[if lt IE 7 ]> <html class="ie6 ie"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7 ie"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8 ie"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9 ie"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html class="no-ie"> <!--<![endif]-->

有关原因,请参阅上面的link

【讨论】:

  • 很有趣,但它让我感到疑惑
  • 我看到很多网站都使用这种方法。只需像其他浏览器一样添加常规条件语句。对吗?
  • @SearchForKnowledge 不幸的是,我不记得为什么会出现这种情况的解释(这有点复杂,html5-boilerplate 的 github-repo 上有一个线程),但最后一个元素也正在为普通浏览器呈现。
  • 再想一想,我其实有点喜欢。让我反胃的是它会影响html 元素。我可能会让它更改一个包含所有内容的 div 元素。
  • @JeremyCook 好吧,你不应该把它放在文档类型之前。文章中描述的 IE6 存在一个问题,如果您使用上一个示例的形式,则不会出现该问题。
【解决方案2】:

使用条件 cmets 以非 IE 为目标。

<!--[if !IE]> -->
According to the conditional comment this is not IE 5-9
<!-- <![endif]-->

你还可以做更高级的事情:http://www.impressivewebs.com/conditional-comments/

【讨论】:

  • 我接受这个答案...因为我想为 !IE 和其他浏览器定位一些东西。谢谢。
【解决方案3】:

您可以在HTML页面中添加IE浏览器的CSS条件语句,而不是在CSS文件中..

针对 IE 8 和更高版本

<!--[if gt IE 7]>
    <link rel="stylesheet" type="text/css" href="ie8-and-up.css" />
<![endif]-->

<!--[if gte IE 8]>
    <link rel="stylesheet" type="text/css" href="ie8-and-up.css" />
<![endif]-->

【讨论】:

  • 请记住,IE10+ 不支持条件 cmets(这是正确的)
猜你喜欢
  • 2015-01-05
  • 2017-10-30
  • 2015-01-31
  • 2013-10-18
  • 1970-01-01
  • 2018-02-24
  • 2015-12-24
  • 1970-01-01
  • 2016-12-01
相关资源
最近更新 更多