将元素颜色重置为默认样式表颜色(jQuery、JavaScript)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2500500/
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
Reset element color to default stylesheet color (jQuery, JavaScript)
提问by cweston
I need to be able to reset an input field back to its original color after it has been possibly changed via javascript to a different value. The problem is I do not want to hard code the value in case the stylesheet changes. I would like to use the default color used on the page.
在输入字段可能已通过 javascript 更改为其他值后,我需要能够将其重置回其原始颜色。问题是我不想在样式表更改的情况下对值进行硬编码。我想使用页面上使用的默认颜色。
Is resetting the color like this fine, or is there a better way to do this?
像这样重置颜色很好,还是有更好的方法来做到这一点?
$('#theinput').css('color', '');
回答by Alsciende
There's no better way. It's the standard way.
没有更好的办法。这是标准的方式。
Basically, there's no way to delete a CSS attribute from the style property of DOM elements. So all you can do is set the attribute value to empty and let CSS do its job of reverting back to the stylesheet.
基本上,没有办法从 DOM 元素的 style 属性中删除 CSS 属性。因此,您所能做的就是将属性值设置为空,并让 CSS 完成恢复到样式表的工作。
回答by Paul D. Waite
If you wanted to do it in plain JavaScript, you could do:
如果你想用纯 JavaScript 来做,你可以这样做:
document.getElementById('theinput').style.color = '';
The only issue with this, or your jQuery method, is if the HTML has a styleattribute that sets the colorCSS property. If you wanted to preserve that, you'd have to store it on page load.
这个或您的 jQuery 方法的唯一问题是 HTML 是否具有style设置colorCSS 属性的属性。如果你想保留它,你必须在页面加载时存储它。
But if it's alright to assume there isn't a style attribute, then you're golden.
但是,如果可以假设没有样式属性,那么您就是黄金。
回答by Avinash
Fine, but you have to specify the color inside quote and id of the input on what color should change.
很好,但是您必须指定引号内的颜色和输入的 id 应更改什么颜色。
This will work :)
这将工作:)
$("#InputIdName").css('color', '#979797');

