我们有一个喜欢插入内联样式的CMS,我编写了一些删除内联样式的代码,添加了一个类,并将样式属性的内容重写为头部的样式标记。
示例HTML
<html>
<head>
<title>Title</title>
</head>
<body>
<div id="container">
<p style="width: 50%;">Blah blah blah</p>
<p style="font-weight: bold;">Even more blah blah blah</p>
<p>Can I get some blah blah blah</p>
<p>Ooo Ahh blah blah blah</p>
</div>
</body>
</html>
jQuery功能
$.each($('#container [style]'), function(index, el){
var cssText = el.style.cssText;
var className = "auto-class-" + index;
$(el).removeAttr("style");
$(el).addClass(className);
$("<style type='text/css'> ." + className + "{" + cssText + "} </style>").appendTo("head");
})
所需结果HTML
<html>
<head>
<title>Title</title>
<style type="text/css"> .auto-class-1 { width: 50%; } </style>
<style type="text/css"> .auto-class-2 { font-weight: bold; } </style>
</head>
<body>
<div id="container">
<p class="auto-class-1">Blah blah blah</p>
<p class="auto-class-2">Even more blah blah blah</p>
<p>Can I get some blah blah blah</p>
<p>Ooo Ahh blah blah blah</p>
</div>
</body>
</html>
我所有的好浏览器都按预期工作,但在IE6中,jQuery [style]
选择器似乎抓住了#container
中的所有元素。所以你得到以下内容。
IE6中的结果HTML
<html>
<head>
<title>Title</title>
<style type="text/css"> .auto-class-1 { width: 50%; } </style>
<style type="text/css"> .auto-class-2 { font-weight: bold; } </style>
<style type="text/css"> .auto-class-3 { } </style>
<style type="text/css"> .auto-class-4 { } </style>
</head>
<body>
<div id="container">
<p class="auto-class-1">Blah blah blah</p>
<p class="auto-class-2">Even more blah blah blah</p>
<p class="auto-class-3">Can I get some blah blah blah</p>
<p class="auto-class-4">Ooo Ahh blah blah blah</p>
</div>
</body>
</html>
在上面的示例中,这不会引起任何问题,但在我们的网站上,任何给定页面上有超过300个DOM节点,这是一团糟。
问题是如何在IE6中仅选择具有样式属性的DOM节点。
还有一种简单的方法可以将所有规则写入一个样式标记,而不是为每个规则分别设置样式标记。
答案 0 :(得分:2)
这不是您提出的具体问题的答案,但 我认为您应该这样做。
你在评论中说:
适用于打印样式表。该 内联样式覆盖它们,但是 风格标签很好。
您正在使用的解决方案(将内联样式移动到<style>
元素)不是很优雅。
在打印样式表中的每个声明中添加!important
会更好。
body {
color: #444 !important;
padding: 0 !important;
margin: 0 !important;
}
#menu {
display: none !important;
}
是的,这很难看,但它比基于JavaScript的解决方案更清晰。
如果您想了解一些背景信息:
请参阅: http://css-tricks.com/specifics-on-css-specificity/
!important附加了一个CSS 财产价值是自动获胜。的它 甚至覆盖了内联样式 标记。唯一的方法!重要 可以覆盖的值是 另一个!重要规则后来宣布 在CSS中,同等或伟大 否则就是特异性值。