巧用ie条件注释解决浏览兼容问题

左手 posted @ 2012年12月28日 20:47 in 前端开发 with tags jade 前端 浏览器兼容 csshack , 2037 阅读

在做web开发的时候,最头疼的就是处理各种浏览器兼容。尤其是ie低版本的兼容。于是各种 css hack层出不穷。类似 _ * \9 \0一类的,功能是实现的,却让本来写得很整齐的 css 代码变得乱糟糟的。其实用ie的条件注释就可以很简单的解决处理这些问题。

示例:

<!DOCTYPE html>
<html>
  <!--[if lt IE 7]><html class="ie6"><![endif]-->
  <head>
    <meta charset="utf-8">
    <title>css hack</title>
    <style>
      .test {height: 40px; background: blue;}
      .ie6 .test {background: red;}
    </style>
  </head>
  <body>
    <p class="test"></p>
  </body>
</html>

上例中通过 ie的条件注释,给 html 标签加上指定的 class ,后面写样式的时候,只需前缀class锚定特定浏览器即可。

附一个jade描述版的较全的浏览器判断。

doctype 5
html
  // if lt IE 7
    |<html class="ie ie6 ltie9">
  // if IE 7
    |<html class="ie ie7 ltie9">
  // if IE 8
    |<html class="ie ie8 ltie9">
  // if gte IE 9
    |<html class="ie ie9">
  head
    meta(charset="utf-8")
    title css hack
  body
    p css hack

有关jade的相关信息,可以参考这里 https://github.com/visionmedia/jade

*2013年2月7日更新

去除示例代码中的ie10判断,经测试发现ie10无法使用ie条件注释(看来微软是下决心净身了)。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter