2014-02-27 92 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');