使用Javascript | jQuery删除特定的内联样式

使用Javascript | jQuery删除特定的内联样式

问题描述:

我的html中包含以下代码:

I have the following code in my html:

<p id='foo' style='text-align:center; font-size:14pt; font-family:verdana; color:red'>hello world</p>

以及我的外部CSS中的内容:

and that in my external css:

#foo{ font-size:11pt; font-family:arial; color:#000; }

我想删除样式"属性中的所有字体大小"和字体系列",但不删除颜色"和外部CSS中设置的其他字体.

I want to remove all "font-size" and "font-family" in the "style" atribute, but not the "color" and others setted in external css.

预期结果:

<p id='foo' style='text-align:center; color:red'>hello world</p>

已尝试:

Already tried:

$('#foo').removeAttr('style');   // That removes all inline
$('#foo').css('font-family',''); // That remove the css setted too

对于不使用jQuery的用户,可以使用本机

For those that aren't using jQuery, you can delete specific styles from the inline styles using the native removeProperty method. Example:

elem.style.removeProperty('font-family');

当然,IE< 9不支持此功能,因此您必须使用

Of course, IE < 9 doesn't support this so you'll have to use

elem.style.removeAttribute('font-family');

所以跨浏览器的方法是:

so a cross browser way to do it would be:

if (elem.style.removeProperty) {
    elem.style.removeProperty('font-family');
} else {
    elem.style.removeAttribute('font-family');
}