如何使用javascript擦除所有内联样式并仅保留css样式表中指定的样式?

Mat*_*att 92 javascript css jquery inline

如果我的html中有以下内容:

<div style="height:300px; width:300px; background-color:#ffffff;"></div>
Run Code Online (Sandbox Code Playgroud)

这在我的css样式表中:

div {
    width:100px;
    height:100px;
    background-color:#000000;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法,使用javascript/jquery,删除所有内联样式,只留下由CSS样式表指定的样式?

Tyl*_*ter 161

$('div').attr('style', '');

要么

$('div').removeAttr('style');(来自Andres的回答)

为了使它更小一点,试试这个:

$('div[style]').removeAttr('style');

这应该加快一点,因为它检查div有样式属性.

无论哪种方式,如果你有大量的div,这可能需要一些时间来处理,所以你可能想要考虑除了javascript之外的其他方法.

  • @streetlight使用`$('*').removeAttr('style')`来定位所有内容. (2认同)

Jos*_*ier 28

普通的JavaScript:

你不需要jQuery来做这样的微不足道的事情.只需使用该.removeAttribute()方法.

假设您只是针对单个元素,您可以轻松使用以下内容:( 示例)

document.querySelector('#target').removeAttribute('style');
Run Code Online (Sandbox Code Playgroud)

如果您要定位多个元素,只需遍历选定的元素集合:( 示例)

var target = document.querySelectorAll('div');
Array.prototype.forEach.call(target, function(element){
    element.removeAttribute('style');
});
Run Code Online (Sandbox Code Playgroud)

Array.prototype.forEach()- IE9及以上/ .querySelectorAll()- IE 8(部分)IE9及以上版本.


and*_*lzo 22

$('div').removeAttr('style');
Run Code Online (Sandbox Code Playgroud)