我正在用jQuery改变CSS,我希望删除我根据输入值添加的样式:

if(color != '000000') $("body").css("background-color", color); else // remove style ?

我该怎么做呢? 请注意,每当使用颜色选择器选择颜色时,上面的行就会运行。当鼠标移动到一个色轮上时)。

第二注意:我不能这样做与css("background-color", "none"),因为它将删除默认样式从css文件。 我只是想删除jQuery添加的背景色内联样式。


当前回答

在web开发中,简单是便宜的。我建议在删除特定样式时使用空字符串

$(element).style.attr = '  ';

其他回答

将属性更改为空字符串似乎可以完成工作:

$.css("background-color", "");

只是用:

$('.tag-class').removeAttr('style');

or

$('#tag-id').removeAttr('style');
let el = document.querySelector(element)
let styles = el.getAttribute('style')

el.setAttribute('style', styles.replace('width: 100%', ''))

在我的测试中,接受的答案可以工作,但在DOM上留下一个空的样式属性。没什么大不了的,但这就完全消除了:

removeAttr( 'style' );

这假设您希望删除所有动态样式并返回到样式表样式。

我讲了用纯JavaScript删除样式属性的方法让你们知道纯JavaScript的方法

var bodyStyle = document.body.style;
if (bodyStyle.removeAttribute)
    bodyStyle.removeAttribute('background-color');
else        
    bodyStyle.removeProperty('background-color');