您可以删除所有style
属性,但是通过你表现的选择,然后检测display: none
和删除样式后重申其保持现有display: none
标志:
$("div[style]").each(function() {
var hide = this.style.display === "none";
$(this).removeAttr("style");
if (hide) {
this.style.display = "none";
}
});
或者更一般地说,保持display
财产不管其价值:
$("div[style]").each(function() {
var display = this.style.display;
$(this).removeAttr("style");
this.style.display = display;
});
完整的示例:Fiddle
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<meta charset=utf-8 />
<title>Style Update</title>
</head>
<body>
<div>No style</div>
<div style="color: green">Green</div>
<div style="color: red; display: none">Red, hidden</div>
<div><button type="button" id="processStyle">Process style attributes</button></div>
<div><button type="button" id="showHidden">Show hidden briefly</button></div>
<p>Click "Show hidden briefly" first, then "Process style attribuets", then "Show hidden briefly" again.</p>
<script>
$("#processStyle").click(function() {
$("div[style]").each(function() {
var display = this.style.display;
$(this).removeAttr("style");
this.style.display = display;
});
});
$("#showHidden").click(function() {
$("div").each(function() {
if (this.style.display === "none") {
$(this).fadeIn('fast').delay(1000).fadeOut('fast');
}
});
});
</script>
</body>
</html>
优秀,高效和完美的作品。谢谢,也修改了问题以引用样式属性(不是标签)。 – neil