如何使用 jQuery 取消元素的 CSS 属性?

如果我使用以下方法在特定元素上设置 CSS 值:

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

我希望能够取消设置特定于元素的值并使用级联值,如下所示:

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

但是这种语法似乎不起作用-这可能使用其他语法吗?

编辑: 该值不是从父元素继承的-原始值来自元素级别的选择器。不好意思,让你们误会了!

54697 次浏览

Try this:

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

Actually, the syntax I thought was incorrect (with null) seems to be working -- my selector was just improperly formed, and thus yielding no elements. D'oh!

I think you can also do:

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

That's what I used to do a long time ago for the display property in plain-old-javascript to show/hide a field.

From the jQuery docs:

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 <style> element.

For what it's worth this appears not to work in IE 8 for 'filter,' I had to use this (in fadeIn callback):

$(this).attr('style', $(this).attr('style').replace(/\bfilter:\s*;*/, ''));

Obviously, I had need to remove an empty inline filter declaration so the CSS could take effect; there were other inline rules so I couldn't just remove the style attribute.

If it can help, I add a problem with double quote :

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

does not work while

$('#element').css('border-color', '');

works