如何使用 javascript 删除所有内联样式并仅保留 css 样式表中指定的样式?
-
22-07-2019 - |
题
如果我的 html 中有以下内容:
<div style="height:300px; width:300px; background-color:#ffffff;"></div>
这在我的 css 样式表中:
div {
width:100px;
height:100px;
background-color:#000000;
}
有没有办法,使用 javascript/jquery 删除所有内联样式,只保留 css 样式表指定的样式?
解决方案
$('div').attr('style', '');
或者
$('div').removeAttr('style');
(从 安德烈斯的回答)
为了让它变小一点,试试这个:
$('div[style]').removeAttr('style');
这应该会加快速度一点,因为它会检查 div 是否具有 style 属性。
无论哪种方式,如果您有大量 div,这可能需要一些时间来处理,因此您可能需要考虑 JavaScript 之外的其他方法。
其他提示
纯 JavaScript:
你不需要 jQuery 来做这样的小事。只需使用 .removeAttribute()
方法。
假设您只针对单个元素,您可以轻松使用以下内容: (例子)
document.querySelector('#target').removeAttribute('style');
如果您要定位多个元素,只需循环遍历选定的元素集合: (例子)
var target = document.querySelectorAll('div');
Array.prototype.forEach.call(target, function(element){
element.removeAttribute('style');
});
Array.prototype.forEach()
- IE9及以上/ .querySelectorAll()
- IE 8(部分)IE9及以上版本。
$('div').removeAttr('style');
我用的是$('div').attr('style', '');
技术和它未在工作IE8
我输出使用alert()
style属性和它不剥出内嵌样式。
.removeAttr
最终做特技在IE8。
如果您需要再元素的只是空style
:点击element.style.cssText = null;
结果这应该做的不错。希望它可以帮助!
这可以通过两个步骤完成:
1:通过标记名、id、类等选择要更改的元素。
var element = document.getElementsByTagName('h2')[0];
- 删除样式属性
element.removeAttribute('style');
您也可以尝试在样式表作为上市CSS!重要