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

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

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

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


当前回答

只是用:

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

or

$('#tag-id').removeAttr('style');

其他回答

试试这个:

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

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

谢谢

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

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

有几种方法来删除CSS属性使用jQuery:

1. 将CSS属性设置为默认值(初始值)

.css("background-color", "transparent")

请参阅MDN上CSS属性的初始值。 这里的默认值是透明的。您还可以对多个CSS属性使用inherit来从其父属性继承该属性。在CSS3/CSS4中,你也可以使用initial, revert或unset,但是这些关键字可能只有有限的浏览器支持。

2. 删除CSS属性

空字符串删除CSS属性,即。

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

但是要注意,正如jQuery . CSS()文档中指定的那样,这将删除属性,但对于某些CSS简写属性(包括background),它与IE8的兼容性存在问题。

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or element. Warning: one notable exception is that, for IE 8 and below, removing a shorthand property such as border or background will remove that style entirely from the element, regardless of what is set in a stylesheet or element.

3.删除元素的整个样式

.removeAttr("style")

如果你使用CSS样式,你可以使用:

$("#element").css("background-color","none"); 

然后替换为:

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

如果你不使用CSS样式,你在HTML元素中有属性,你可以使用:

$("#element").attr("style.background-color",color);

这个也可以!!

$elem.attr('style','');