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

使用Javascript | jQuery删除特定的内联样式,javascript,jquery,Javascript,Jquery,我的html中有以下代码: <p id='foo' style='text-align:center; font-size:14pt; font-family:verdana; color:red'>hello world</p> 我想删除样式中的所有字体大小和字体系列,但不删除外部css中的颜色和其他设置 预期结果: <p id='foo' style='text-align:center; color:red'>hello world</p>

我的html中有以下代码:

<p id='foo' style='text-align:center; font-size:14pt; font-family:verdana; color:red'>hello world</p>
我想删除
样式
中的所有
字体大小
字体系列
,但不删除外部css中的
颜色
和其他设置

预期结果:

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

我认为这个问题没有合适的解决方案(不更改标记)。可以搜索并替换样式属性的值:

var element = $('#foo');
element.attr('style', element.attr('style').replace(/font-size:[^;]+/g, '').replace(/font-family:[^;]+/g, ''))

到目前为止,最好的解决方案是摆脱内联样式,并使用类管理样式。

我的建议是不要使用内联样式设置这些内容。我建议使用类,然后使用jQuery在它们之间切换:

CSS:

HTML:


将属性设置为继承:

$('#foo').css('font-family','inherit').css('font-size','inherit');

从我看来,你真的需要两种不同的风格的段落。在CSS中设置这些内容可能更容易,然后根据需要使用jQuery删除/添加:

#styleOne { color: red; font: normal 14pt Verdana; text-align: center; }

#styleTwo{ color: #000; font: normal 11pt Arial; text-align: center; }
您的初始html将如下所示:

<p id="styleOne">hello world</p>

对于那些不使用jQuery的用户,可以使用本机方法从内联样式中删除特定样式。例如:

elem.style.removeProperty('font-family');
当然,IE<9不支持此功能,因此您必须使用

elem.style.removeAttribute('font-family');
因此,跨浏览器的方法是:

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

2019年,移除房产的最简单方式似乎是:

elem.style.border = "";
同样,要设置边框,请执行以下操作:

elem.style.outline = "1px solid blue";

也应该适用于所有浏览器

动态添加和删除内联样式属性

var检查=()=>{
console.log('test')
var el=document.getElementById(“id”);
变量条件=el.style['color']!=“”?真:假;
如果(条件){
el.style.removeProperty('color')
}
否则{
el.style.color=“红色”
}
}
动态样式

应用样式
非常感谢,它将永远帮助我。。。我使用的cms允许用户使用tinyMCE设置他想要的文本内容。
inherit
应该从父级继承值,而不是从一种不太常见的样式继承值rule@GetFree这是对的。您可能不想使用
inherit
。想象一下,如果在列表项中的div上设置
div.style.display='inherit'
,该div将以
display:list item
结束,这几乎肯定不是您想要的。+1这肯定解决了问题,而不是公认的答案。然而,您的旧IE回退应该是
elem.style.removeAttribute('fontFamily')我相信..+1绝对是最好的答案
elm.style.removeProperty()
elm.style.setProperty()
。谢谢你的提醒,我甚至不知道removeProperty。。。卢兹,谢谢你,本@John请停止编辑有关JavaScript的问题的JavaScript标记。
$('p#styleOne').removeClass('styleOne').addClass('styleTwo');
elem.style.removeProperty('font-family');
elem.style.removeAttribute('font-family');
if (elem.style.removeProperty) {
    elem.style.removeProperty('font-family');
} else {
    elem.style.removeAttribute('font-family');
}
elem.style.border = "";
elem.style.outline = "1px solid blue";