您可以刪除所有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