首先,免责声明。我并不真正提倡我在下面提出的解决方案。我编写的唯一特定于浏览器的 CSS 是针对 IE(尤其是 IE6)的,尽管我希望不是这样。
现在,解决方案。你要求它优雅,所以我不知道它有多优雅,但它肯定只会针对 Gecko 平台。
这个技巧只有在启用 JavaScript 并使用 Mozilla 绑定 ( XBL ) 时才有效,这些绑定在 Firefox 和所有其他基于 Gecko 的产品内部大量使用。作为比较,这类似于IE中的behavior CSS属性,但功能更强大。
我的解决方案涉及三个文件:
- ff.html:要设置样式的文件
- ff.xml:包含 Gecko 绑定的文件
- ff.css:Firefox 特定样式
ff.html
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
-moz-binding: url(ff.xml#load-mozilla-css);
}
</style>
</head>
<body>
<h1>This should be red in FF</h1>
</body>
</html>
ff.xml
<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl">
<binding id="load-mozilla-css">
<implementation>
<constructor>
<![CDATA[
var link = document.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "ff.css");
document.getElementsByTagName("head")[0]
.appendChild(link);
]]>
</constructor>
</implementation>
</binding>
</bindings>
ff.css
h1 {
color: red;
}
更新:
上述解决方案不是很好。如果不是附加一个新的 LINK 元素,而是在 BODY 元素上添加那个“firefox”类,那就更好了。这是可能的,只需将上面的 JS 替换为以下内容:
this.className += " firefox";
该解决方案的灵感来自Dean Edwards 的 moz-behaviors。