jQuery CSS:动态更改类的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14477746/
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
jQuery CSS: Dynamically change attributes of a class
提问by Marl
I want to change the attribute of a class on which all element that use the class for the rest of the web application life (from start of use until the user exits the web application) will be affected.
我想更改一个类的属性,在该属性上,在 Web 应用程序生命周期的剩余时间(从使用开始到用户退出 Web 应用程序)使用该类的所有元素都将受到影响。
html:
html:
<p class="myClass">
What?
</p>
<p class="myClass">
Now?
</p>
css:
css:
.myClass{
background-color: #ffff00;
}
js:
js:
$(".myClass").css("background-color", "#00FFFF");
$("p").last().after("<div class='myClass'>Now!</div>");
What I want to achieve from the sample is that all subsequent dynamically added myClass will have the new attribute. From the jsFiddle, you'll see that the next added element doesn't have the new attribute.
我想从示例中实现的是,所有后续动态添加的 myClass 都将具有新属性。从 jsFiddle 中,您将看到下一个添加的元素没有新属性。
MORE:
更多的:
I'm just using the color for a basis, I will implement this in larger scale, what I want to accomplish is to dynamically change the attributes of a class that will be used for the entire web app life cycle.
我只是使用颜色作为基础,我将在更大范围内实现它,我想要完成的是动态更改将用于整个 Web 应用程序生命周期的类的属性。
采纳答案by adeneo
Using the css() method changes the inline styles on already existing elements, and you can't use that to change the styles on future elements. A workaround (that I don't like very much) would be to insert a style tag:
使用 css() 方法会更改现有元素的内联样式,您不能使用它来更改未来元素的样式。一种解决方法(我不太喜欢)是插入一个样式标签:
$( "<style>.myClass {background-color : #00FFFF}</style>" ).appendTo( "head" )
$("p").last().after("<div class='myClass'>Now!</div>");
回答by DaveInMaine
I just stumbled upon this question, and thought I would chime in, even though it is almost a year old...
我只是偶然发现了这个问题,并以为我会插话,即使它已经快一年了......
You actually can modify the css rules dynamically at runtime, just like any other DOM element. I don't think jQuery supports it, so you would need to use the native DOM elements directly.
您实际上可以在运行时动态修改 css 规则,就像任何其他 DOM 元素一样。我认为 jQuery 不支持它,因此您需要直接使用本机 DOM 元素。
You can assign titles to stylesheets to make them easier to locate in the DOM tree, but with a little forethought, it's usually not too difficult to find the rules you want. Here is a quick example from a jsfiddle based on your example.
您可以为样式表分配标题,使它们更容易在 DOM 树中定位,但只要稍加考虑,通常不难找到您想要的规则。这是一个基于您的示例的 jsfiddle 的快速示例。
function getStyleRule(name) {
for(var i=0; i<document.styleSheets.length; i++) {
var ix, sheet = document.styleSheets[i];
for (ix=0; ix<sheet.cssRules.length; ix++) {
if (sheet.cssRules[ix].selectorText === name)
return sheet.cssRules[ix].style;
}
}
return null;
}
var rule = getStyleRule('.myClass');
rule.backgroundColor = '#0ff';
$("p").last().after("<div class='myClass'>Now!</div>");
Here is a fiddle that shows your example, updated to modify the css rule itself: http://jsfiddle.net/93wGJ/5/
这是一个显示您的示例的小提琴,已更新以修改 css 规则本身:http: //jsfiddle.net/93wGJ/5/
For more info on the DOM for stylesheets, have a look at http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html
有关样式表 DOM 的更多信息,请查看http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html
回答by Marcin Bobowski
Try putting color change in a function:
尝试在函数中添加颜色变化:
function colorChange() {
$(".myClass").css("background-color", "#00FFFF");
}
And call it "on load" and after You change something with jQuery.
并将其称为“加载时”,然后在您使用 jQuery 更改某些内容之后。
回答by Viktor S.
I would do something like below. It does not modify class, but it does what you need.
我会做类似下面的事情。它不会修改类,但可以满足您的需求。
$("body").addClass("updatedClass");
$("p").last().after("<div class='myClass'>Now!</div>");
and css:
和CSS:
.myClass{
background-color: #ffff00;
}
.updatedClass .myClass {
background-color: #00FFFF;
}
In any case, if you want to keep this enabled for any page, you should do this with server being involved. For instance, by setting some variable into a session and than returning corresponding css based on that variable.
在任何情况下,如果您想为任何页面启用此功能,您应该在涉及服务器的情况下执行此操作。例如,通过将一些变量设置到会话中,然后根据该变量返回相应的 css。
Or you can use cookies (check jquery cookiesplugin for simpler access to cookies on client side) and modify class with inserting style tag or by adding corresponding class to body in jQuery.ready callback.
或者您可以使用 cookie(检查jquery cookie插件以更简单地访问客户端的 cookie)并通过插入样式标记或通过在 jQuery.ready 回调中将相应的类添加到主体来修改类。
for instance, with cookies (using plugin mentioned above) code could be like this:
例如,使用 cookie(使用上面提到的插件)代码可能是这样的:
$("body").addClass("updatedClass");
$("p").last().after("<div class='myClass'>Now!</div>");
$.cookie('baseClass', 'updatedClass'); // set class for current session (this cookie will be deleted after user ends his session)
and than, each page should have:
然后,每个页面都应该有:
$(function() {
if($.cookie('baseClass') != null) {
$("body").addClass($.cookie('baseClass'));// or style tag could be added here instead.
}
})
回答by Jai
Try with this: http://jsfiddle.net/tRqBV/5/
试试这个:http: //jsfiddle.net/tRqBV/5/
$(function () {
$(".myClass").css("background", "green");
$("p").last().after("<div class='myClass'>Now!</div>");
$(document).ready(function () {
$('div.myClass').css("background", $('p.myClass').first().css('background-color'));
});
});
回答by Regular Joe
I had this same goal on mind, I use hashes + ajax to navigation recordsets and I wanted viewing preferences of recordsets to be saved easily. (I wanted links to removable if the user preferred to navigate the records with links, or invisible if they chose).
我有同样的目标,我使用哈希 + ajax 来导航记录集,我希望可以轻松保存查看记录集的首选项。(如果用户喜欢使用链接浏览记录,我希望链接可移动,或者如果他们选择不可见)。
DaveInMaine'sanswer is great but I worry a bit about backwards compatibility so I strove for a simple solution.
DaveInMaine 的回答很好,但我有点担心向后兼容性,所以我努力寻找一个简单的解决方案。
By naming my table, a static element, recordTable
, giving it a class of LinksOn
and I can use style selectors like #recordTable.LinksOn a
and #recordTable.LinksOff a
with display set to none, and use a simple javascript like
通过命名我的表,静态元素recordTable
,给它一个类的LinksOn
,我可以使用的样式选择喜欢#recordTable.LinksOn a
和#recordTable.LinksOff a
与显示器设置为无,并使用一个简单的JavaScript像
javascript:$('#recordTable').toggleClass('LinksOn').toggleClass('LinksOff');
By storing the last class in a variable in a cookie, server-side session via ajax, or localStorage, I can save it between sessions if I like.
通过将最后一个类存储在 cookie、服务器端会话通过 ajax 或 localStorage 的变量中,如果我愿意,我可以在会话之间保存它。
I could do this all with a single class (#recordtable
and #recordtable.on
, rather than on
and off
), but I chose to store it this way.
我可以用一个类(#recordtable
and #recordtable.on
,而不是on
and off
)来完成这一切,但我选择以这种方式存储它。
回答by Sulot
In addition to what have been said, I think it would be useless to modify a css rule because the already existing elements wouldn't be modified.
除了已经说过的,我认为修改 css 规则是没有用的,因为不会修改已经存在的元素。
<style>
.myclass{
font-size:25px;
}
</style>
<div class="myclass">I am here </div>
Now, if you modify somehow the class "myclass" itselef, it wouldn't affect "I am here", because it is not dynamically binded. Perhaps it would affect the newly created elements.
现在,如果您以某种方式修改“myclass”类本身,它不会影响“我在这里”,因为它不是动态绑定的。也许它会影响新创建的元素。