2014-02-27 97 views
3

我們的表單軟件會生成大量內聯style屬性,我想刪除它們。我知道這可以用$('div[style]').removeAttr('style')之類的東西很快完成,但不幸的是,我需要保留所有display:none,因爲這些可以在稍後顯示,具體取決於條件選擇。jQuery:刪除特定樣式標記

基於https://stackoverflow.com/questions/2465158/is-it-possible-to-remove-inline-styles-with-jquery,我知道像$('div').css('color', '');的工作,但我需要重複進行font-sizetext-align

那麼,這將是一個更有效的方式(使用jQuery,最好)至刪除所有樣式標籤不是display,最好在鏈/單行語句中?我想過使用:not但無法弄清楚如何與上面的例子結合起來......

感謝

回答

4

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

優秀,高效和完美的作品。謝謝,也修改了問題以引用樣式屬性(不是標籤)。 – neil

2

你可以做的是保存你想要的樣式(或樣式),將它們全部刪除,然後再次設置存儲的樣式。 事情是這樣的:

$('.selector').each(function() { 
var keepStyle, $el; 
    $el = $(this); 
    keepStyle = { 
    display: $el.css('display')//use comma seprated css style for multiple style 
    }; 

$el.removeAttr('style') 
    .css(keepStyle); 
}) 
0
none = false; 
if($(selector).css('display')=='none') 
    none = true; 
$(selector).removeAttr('style'); 
if(none) 
    $(selector).css('display','none');