1
我们有一个喜欢插入内联样式的CMS,我已经编写了一些删除内联样式的代码,添加了一个类并将样式属性的内容重写为样式标签在头部。如何使用jQuery在IE6中选择具有样式标记的元素
例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>
<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>
结果HTML在以上示例不会导致那里有任何给定的页面超过300 DOM节点这是一个混乱的任何问题,但在我们的网站。
问题是我如何才能在IE6中只选择带有样式属性的DOM节点。
还有一种简单的方法可以将所有规则写入一个样式标签,而不是为每个规则分别设置样式标签。
为什么要将内联样式移动到使用jQuery的单个'