jQuery 如何向现有类添加属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6718484/
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 to add property to existing class
提问by Alex
I have got a CSS class like so:
我有一个像这样的 CSS 类:
.simpleClass {
width: 25px;
}
And I have a matching element:
我有一个匹配的元素:
<div class="simpleClass"></div>
Can I add the property display: none;
to the CSS class .simpleClass
dynamically through jQuery? Thanks.
我可以通过 jQuery 动态地将属性添加display: none;
到 CSS 类.simpleClass
吗?谢谢。
回答by Rafay
you can specify the style of the element by using .css
like
您可以使用.css
like指定元素的样式
$("div.simpleClass").css("width","25px");
have a look at jQuery.css()
回答by Steven Palinkas
If I get it right, You don't want to give property to the instance element of simpleClass
, but would like to give an extra property to the whole class ( covering all instances ) using JS.
如果我做对了,您不想为 的实例元素提供属性simpleClass
,而是想使用 JS 为整个类(覆盖所有实例)提供额外的属性。
In this case, You can use jQuery to append a style element to the head, giving You the opportunity to add additional CSS declarations.
在这种情况下,您可以使用 jQuery 将样式元素附加到头部,让您有机会添加额外的 CSS 声明。
However, I would notrecommend this, because it causes Your code, and structure to get messy.
但是,我不建议这样做,因为它会导致您的代码和结构变得混乱。
$("head").append("<style> .simpleClass{ display:none; } </style>");
This snippet will give extra display:none
property to all .simpleClass
elements existing in the time of doing this, and will also affect every later-inserted .simpleClass
elements.
此代码段将为执行此操作时存在的display:none
所有.simpleClass
元素提供额外的属性,并且还将影响每个以后插入的.simpleClass
元素。
回答by daryl
$('.simpleClass').css({display:'none'});
回答by domino_katrino
The property will be added to div if it already not exist in css class. Hence, it's always better to switch css class with new properties. Eg.
如果 css 类中不存在该属性,则该属性将被添加到 div 中。因此,使用新属性切换 css 类总是更好。例如。
$( ".referenceClass" ).switchClass( "oldClass", "newClass");
回答by Manuel Leuenberger
The stylesheet is defined in a file, and you can't edit that with JavaScript. What you could do is this:
样式表在文件中定义,您无法使用 JavaScript 对其进行编辑。你可以做的是:
$(".simpleClass").live("domchanged", function() {
$(this).css("display", "none");
});
But this is neither not cross-browser compatiblenor efficient (nor tested by me ;). So I'd propose to use another predefined CSS class for this purpose. Why do you need something like this anyway?
但这既不是跨浏览器兼容的,也不是高效的(也不是我测试过的;)。所以我建议为此使用另一个预定义的 CSS 类。你为什么需要这样的东西?
回答by Alex
$(document).ready(function(){
$(.simpleClass).css('display','none');
});