如何使用 jQuery 取消设置元素的 CSS 属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/490910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I unset an element's CSS attribute using jQuery?
提问by cdleary
If I set a CSS value on a specific element using:
如果我使用以下方法在特定元素上设置 CSS 值:
$('#element').css('background-color', '#ccc');
I want to be able to unset that element-specific value and use the cascaded value, along the lines of:
我希望能够取消设置特定于元素的值并使用级联值,如下所示:
$('#element').css('background-color', null);
But that syntax doesn't seem to work – is this possible using another syntax?
但是这种语法似乎不起作用——这可能使用另一种语法吗?
Edit:The value isn't inherited from the parent element – the original values comes from an element-level selector. Sorry for any confusion!
编辑:该值不是从父元素继承的——原始值来自元素级选择器。抱歉有任何混淆!
回答by Glenn Moss
From the jQuery docs:
来自jQuery 文档:
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 thestyle
property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
将样式属性的值设置为空字符串——例如
$('#mydiv').css('color', '')
——如果该属性已经被直接应用,无论是在 HTML 样式属性中,通过 jQuery 的.css()
方法,还是通过对style
属性的直接 DOM 操作,都会从元素中删除该属性。但是,它不会删除已在样式表或<style>
元素中应用 CSS 规则的样式。
回答by FryGuy
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.
这就是我很久以前display
在纯旧 javascript 中为显示/隐藏字段的属性所做的。
回答by cdleary
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!
实际上,我认为不正确的语法(with null
)似乎有效——我的选择器只是格式不正确,因此没有产生任何元素。哦!
回答by HectorMac
Try this:
尝试这个:
$('#element').css('background-color', 'inherit');
回答by Brandon Hill
For what it's worth this appears not to work in IE 8 for 'filter,' I had to use this (in fadeIn callback):
值得一提的是,这似乎不适用于 IE 8 的“过滤器”,我不得不使用它(在淡入淡出回调中):
$(this).attr('style', $(this).attr('style').replace(/\bfilter:\s*;*/, ''));
$(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.
显然,我需要删除一个空的内联过滤器声明,这样 CSS 才能生效;还有其他内联规则,所以我不能只删除 style 属性。
回答by merlintintin
If it can help, I add a problem with double quote :
如果有帮助,我添加一个双引号问题:
$('#element').css("border-color", "");
does not work while
不工作,而
$('#element').css('border-color', '');
works
作品