Raf*_*ges 59 javascript jquery
我的html中有以下代码:
<p id='foo' style='text-align:center; font-size:14pt; font-family:verdana; color:red'>hello world</p>
Run Code Online (Sandbox Code Playgroud)
在我的外部CSS中:
#foo{ font-size:11pt; font-family:arial; color:#000; }
Run Code Online (Sandbox Code Playgroud)
我想删除"style"属性中的所有"font-size"和"font-family",但不删除外部css中设置的"color"和其他内容.
结果预期:
<p id='foo' style='text-align:center; color:red'>hello world</p>
Run Code Online (Sandbox Code Playgroud)
已经尝试过:
$('#foo').removeAttr('style'); // That removes all inline
$('#foo').css('font-family',''); // That remove the css setted too
Run Code Online (Sandbox Code Playgroud)
Ben*_*n L 105
对于那些不使用jQuery的用户,可以使用本机removeProperty方法从内联样式中删除特定样式.例:
elem.style.removeProperty('font-family');
Run Code Online (Sandbox Code Playgroud)
当然,IE <9不支持这一点,所以你必须使用它
elem.style.removeAttribute('font-family');
Run Code Online (Sandbox Code Playgroud)
所以跨浏览器的方式是:
if (elem.style.removeProperty) {
elem.style.removeProperty('font-family');
} else {
elem.style.removeAttribute('font-family');
}
Run Code Online (Sandbox Code Playgroud)
Guf*_*ffa 14
将属性设置为inherit:
$('#foo').css('font-family','inherit').css('font-size','inherit');
Run Code Online (Sandbox Code Playgroud)
我认为这个问题没有合适的解决方案(不改变你的标记)。您可以搜索和替换样式属性的值:
var element = $('#foo');
element.attr('style', element.attr('style').replace(/font-size:[^;]+/g, '').replace(/font-family:[^;]+/g, ''))
Run Code Online (Sandbox Code Playgroud)
到目前为止,最好的解决方案是摆脱内联样式并通过使用类来管理样式。
小智 6
在 2019 年,删除属性的最简单方法似乎是:
elem.style.border = "";
Run Code Online (Sandbox Code Playgroud)
同样,要设置边框:
elem.style.outline = "1px solid blue";
Run Code Online (Sandbox Code Playgroud)
也应该适用于所有浏览器!