在运行时使用jQuery创建一个CSS规则/类 [英] Create a CSS rule / class with jQuery at runtime
问题描述
通常我有一个CSS文件,它有以下规则:
Usually I have a CSS file which has the following rule:
#my-window {
position: fixed;
z-index: 102;
display:none;
top:50%;
left:50%;
}
如何避免创建这样的静态CSS文件通过添加CSS信息运行时动作到身体,或类似的东西? (只使用jQuery)
How can I avoid creating such a static CSS file by adding the CSS information during runtime actions to the body, or something similar? (only using jQuery)
我想定义一次,但是用jQuery和使用它很多次;这就是为什么我不想每次添加到特定的DOM元素。
I want to define it once but with jQuery and use it many times later; that's why I do not want to add it each time to the specific DOM elements.
我知道简单的功能( css(attr1 value);
),但是如何创建一个完整的可重用的CSS规则?
I know the simple features (css("attr1", "value");
), but how can I create a complete reusable CSS rule?
推荐答案
您可以创建样式元素并将其插入DOM
You can create style element and insert it into DOM
$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
$("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");
在Opera 10 FF3.5 iE8 iE6上测试
tested on Opera10 FF3.5 iE8 iE6
这篇关于在运行时使用jQuery创建一个CSS规则/类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!