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

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

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

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


当前回答

为什么不让你想要删除一个CSS类的样式呢?现在你可以使用:. removeclass()。 这也开启了使用.toggleClass()的可能性:

(如果存在,则删除该类,如果不存在则添加该类。)

在处理布局问题时,添加/删除类也会减少更改/故障排除的混乱(而不是试图找出特定样式消失的原因)。

其他回答

比如:

var myCss = $(element).attr('css');
myCss = myCss.replace('background-color: '+$(element).css('background-color')+';', '');
if(myCss == '') {
  $(element).removeAttr('css');
} else {
  $(element).attr('css', myCss);
}

2018

有本地API

element.style.removeProperty(propery)

只是用:

$('.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%', ''))

试试这个:

$('#divID').css({"background":"none"});// remove existing

$('#divID').css({"background":"#bada55"});// add new color here.

谢谢