如何动态更改类css样式? [英] How to dynamically change a class css styling?
本文介绍了如何动态更改类css样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标
在我的程序中,我想使用jquery / javascript执行这两项操作:
- 动态更改CSS类的样式
- 向元素添加/删除类
问题
要使用 $(。className)。css()
但它只会改变已经有 className
类的元素的样式,即如果我后添加 className
到一个元素,它的样式不会是新的。
示例
请参阅
解决方案
缩短格式:
$(< style />,{text:.redclass {color:darkRed;}})appendTo('head');
代码段:
$(< style />,{text:.redclass {color:darkRed;}})appendTo('head'); $(p)。addClass(redclass) ; $(span)。addClass(redclass);
< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< p>我想成为红! < / p>< span>我想变红,但我不是:'(< / span>
Goal
In my program I want to do both things with jquery/javascript:
- Change styling of css classes dynamically
- Add/remove classes to elements
Problem
To do the first thing I use $(".className").css()
method, but it changes style only for those elements that already have className
class, i.e. if I later add className
to an element its style won't be new. How can I solve this?
Example
See it also at jsfiddle.
$("p").addClass("redclass");
$(".redclass").css("color", "darkRed");
$("span").addClass("redclass");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>
Result:
解决方案
A more shorten format:
$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');
The snippet:
$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');
$("p").addClass("redclass");
$("span").addClass("redclass");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>
这篇关于如何动态更改类css样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文