使用 jQuery 更改 CSS 类属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11474430/
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
Change CSS class properties with jQuery
提问by Alvaro
Is there a way to change the properties of a CSS class, not the element properties, using jQuery?
有没有办法使用 jQuery 更改 CSS 类的属性,而不是元素属性?
This is a practical example:
这是一个实际的例子:
I have a div with class red
我有一个带班级的div red
.red {background: red;}
I want to change class red
background property, not elements that have class red
background assigned.
我想更改类red
背景属性,而不是red
分配了类背景的元素。
If I do it with jQuery .css() method:
如果我使用 jQuery .css() 方法:
$('.red').css('background','green');
it will affect the elements that right now have class red
. Up to here everything is fine.
But if I make an Ajax call, and insert more divs with red
class, those won't have a green background, they will have the initial red
background.
它将影响现在具有 class 的元素red
。到这里一切都很好。但是,如果我进行 Ajax 调用,并在red
类中插入更多 div ,那些将不会有绿色背景,它们将具有初始red
背景。
I could call jQuery .css() methodagain. But I would like to know if there is a way to change the class itself. Please consider this is just a basic example.
我可以再次调用 jQuery .css() 方法。但我想知道是否有办法改变类本身。请考虑这只是一个基本示例。
采纳答案by Dennis Traub
You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.
您不能直接使用 jQuery 更改 CSS 属性。但是您至少可以通过两种方式达到相同的效果。
Dynamically Load CSS from a File
从文件动态加载 CSS
function updateStyleSheet(filename) {
newstylesheet = "style_" + filename + ".css";
if ($("#dynamic_css").length == 0) {
$("head").append("<link>")
css = $("head").children(":last");
css.attr({
id: "dynamic_css",
rel: "stylesheet",
type: "text/css",
href: newstylesheet
});
} else {
$("#dynamic_css").attr("href",newstylesheet);
}
}
The example above is copied from:
上面的例子复制自:
Dynamically Add a Style Element
动态添加样式元素
$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');
The example code is copied from this JSFiddle fiddleoriginally referenced by Alvaro in their comment.
示例代码是从Alvaro在他们的评论中最初引用的这个 JSFiddle fiddle 中复制的。
回答by Mathew Wolf
In case you cannot use different stylesheet by dynamically loading it, you can use this function to modify CSS class. Hope it helps you...
如果您不能通过动态加载来使用不同的样式表,您可以使用此功能来修改 CSS 类。希望能帮到你...
function changeCss(className, classValue) {
// we need invisible container to store additional css definitions
var cssMainContainer = $('#css-modifier-container');
if (cssMainContainer.length == 0) {
var cssMainContainer = $('<div id="css-modifier-container"></div>');
cssMainContainer.hide();
cssMainContainer.appendTo($('body'));
}
// and we need one div for each class
classContainer = cssMainContainer.find('div[data-class="' + className + '"]');
if (classContainer.length == 0) {
classContainer = $('<div data-class="' + className + '"></div>');
classContainer.appendTo(cssMainContainer);
}
// append additional style
classContainer.html('<style>' + className + ' {' + classValue + '}</style>');
}
This function will take any class name and replace any previously set values with the new value. Note, you can add multiple values by passing the following into classValue: "background: blue; color:yellow"
.
此函数将采用任何类名并用新值替换任何先前设置的值。请注意,您可以通过将以下内容传递给 classValue: 来添加多个值"background: blue; color:yellow"
。
回答by drumbumLOLcatz
Didn't find the answer I wanted, so I solved it myself:
modify a container div!
没有找到我想要的答案,所以我自己解决了:
修改一个容器div!
<div class="rotation"> <!-- Set the container div's css -->
<div class="content" id='content-1'>This div gets scaled on hover</div>
</div>
<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>
css you want to persist after executing $target.css()
执行 $target.css() 后要保留的 css
.content:hover {
transform: scale(1.5);
}
modify content's containing div with css()
使用 css() 修改内容的包含 div
$(".rotation").css("transform", "rotate(" + degrees + "deg)");
回答by Ajmal Salim
You can remove classes and add classes dynamically
您可以删除类并动态添加类
$(document).ready(function(){
$('#div').removeClass('left').addClass('right');
});
回答by Benny
$(document)[0].styleSheets[styleSheetIndex].insertRule(rule, lineIndex);
$(document)[0].styleSheets[styleSheetIndex].insertRule(rule, lineIndex);
styleSheetIndex
is the index value that corresponds to which order you loaded the file in the <head>
(e.g. 0 is the first file, 1 is the next, etc. if there is only one CSS file, use 0).
styleSheetIndex
是与您加载文件的顺序相对应的索引值<head>
(例如,0 是第一个文件,1 是下一个文件,等等。如果只有一个 CSS 文件,则使用 0)。
rule
is a text string CSS rule. Like this: "body { display:none; }"
.
rule
是一个文本字符串 CSS 规则。像这样:"body { display:none; }"
。
lineIndex
is the line number in that file. To get the last line number, use $(document)[0].styleSheets[styleSheetIndex].cssRules.length
. Just console.log
that styleSheet object, it's got some interesting properties/methods.
lineIndex
是该文件中的行号。要获取最后一行编号,请使用$(document)[0].styleSheets[styleSheetIndex].cssRules.length
. 只是console.log
那个 styleSheet 对象,它有一些有趣的属性/方法。
Because CSS is a "cascade", whatever rule you're trying to insert for that selector you can just append to the bottom of the CSS file and it will overwrite anything that was styled at page load.
因为 CSS 是一个“级联”,无论您尝试为该选择器插入什么规则,您都可以将其附加到 CSS 文件的底部,它会覆盖页面加载时设置的任何样式。
In some browsers, after manipulating the CSS file, you have to force CSS to "redraw" by calling some pointless method in DOM JS like document.offsetHeight
(it's abstracted up as a DOM property, not method, so don't use "()") -- simply adding that after your CSSOM manipulation forces the page to redraw in older browsers.
在某些浏览器中,在操作 CSS 文件后,您必须通过调用 DOM JS 中的一些毫无意义的方法来强制 CSS“重绘” document.offsetHeight
(它被抽象为 DOM 属性,而不是方法,所以不要使用“()”) -- 只需在 CSSOM 操作强制页面在旧浏览器中重绘之后添加即可。
So here's an example:
所以这是一个例子:
var stylesheet = $(document)[0].styleSheets[0];
stylesheet.insertRule('body { display:none; }', stylesheet.cssRules.length);
var stylesheet = $(document)[0].styleSheets[0];
stylesheet.insertRule('body { display:none; }', stylesheet.cssRules.length);
回答by Welly
You can add a class to the parent of the red div, e.g. green-style
您可以将一个类添加到红色 div 的父级,例如 green-style
$('.red').parent().addClass('green-style');
then add style to the css
然后在css中添加样式
.green-style .red {
background:green;
}
so everytime you add red element under green-style, the background will be green
所以每次你在green-style下添加红色元素,背景都会是绿色的
回答by Justin MacArthur
Here's a bit of an improvement on the excellent answer provided by Mathew Wolf. This one appends the main container as a style tag to the head element and appends each new class to that style tag. a little more concise and I find it works well.
这是对 Mathew Wolf 提供的优秀答案的一些改进。这个将主容器作为样式标签附加到 head 元素,并将每个新类附加到该样式标签。更简洁一点,我发现它运作良好。
function changeCss(className, classValue) {
var cssMainContainer = $('#css-modifier-container');
if (cssMainContainer.length == 0) {
var cssMainContainer = $('<style id="css-modifier-container"></style>');
cssMainContainer.appendTo($('head'));
}
cssMainContainer.append(className + " {" + classValue + "}\n");
}
回答by checkmate711
You may want to take a different approach: Instead of changing the css dynamically, predefine your styles in CSS the way you want them. Then use JQuery to add and remove styles from within Javascript. (see code from Ajmal)
您可能需要采用不同的方法:不要动态更改 css,而是按照您希望的方式在 CSS 中预定义样式。然后使用 JQuery 在 Javascript 中添加和删除样式。(见 Ajmal 的代码)