简体   繁体   English

在jQuery中创建一个新的(permenant)CSS样式

[英]Create a new (permenant) CSS style in jQuery

I want to create a new style, not just alter the style attribute of an element. 我想创建一个新样式,而不仅仅是改变元素的style属性。 Here's some example code to demonstrate the problem: 以下是一些示例代码来演示此问题:

//Create 1st element
var element1 = $('<div />').text('element1').addClass('blue');
$('body').append(element1);

//Set some css for all elements with the blue class
$('.blue').css('background-color', 'blue');

//Create 2nd element, it won't have the css applied because it wasn't around when the css was set
var element2 = $('<div />').text('element2').addClass('blue');
$('body').append(element2);​

In the code above the 2nd element does not have the same style as the 1st. 在上面的代码中,第二个元素与第一个元素的风格不同。 What I would like is to be able to set the css on a className for all future elements. 我想要的是能够为所有未来的元素在className上设置css。

JSFiddle 的jsfiddle

You could create a new stylesheet and append this to the head: 您可以创建一个新的样式表并将其附加到头部:

$("<style type='text/css'> .blue{ background-color:blue;} </style>").appendTo("head");

See Demo: http://jsfiddle.net/YenN4/2/ 见演示: http//jsfiddle.net/YenN4/2/

Demo: http://jsfiddle.net/T6KEW/ 演示: http//jsfiddle.net/T6KEW/

$('<style>').text('.blue { background: blue }').appendTo('head');

$('<div>').text('element1').addClass('blue').appendTo('body');
$('<div>').text('element2').addClass('blue').appendTo('body');​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM