[英]How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?
如果我的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');
(来自Andres的回答 )
为了使它更小一点,试试这个:
$('div[style]').removeAttr('style');
这应该加快一点,因为它检查div有样式属性。
无论哪种方式,如果你有大量的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');
如果您只需要清空元素的style
,那么:
element.style.cssText = null;
这应该做得很好。 希望能帮助到你!
我正在使用$('div').attr('style', '');
技术,它在IE8中不起作用。
我使用alert()
输出了style属性,并没有删除内联样式。
.removeAttr
最终在IE8中完成了这个技巧。
这可以通过两个步骤完成:
1:通过标记名,ID,类等选择要更改的元素。
var element = document.getElementsByTagName('h2')[0];
element.removeAttribute('style');
您还可以尝试将样式表中的css列为!important
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.