2012-09-18 9 views
6

Voglio creare un nuovo stile, non solo alterare l'attributo di stile di un elemento. Ecco alcuni esempi di codice per dimostrare il problema:Creare un nuovo stile CSS (permenant) in jQuery

//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);​ 

Nel codice di sopra del 2 ° elemento non ha lo stesso stile del primo. Quello che vorrei è essere in grado di impostare il css su un className per tutti gli elementi futuri.

JSFiddle

+0

possibile duplicato di [ Aggiungi ad una classe css usando JQuery] (http: // stackov erflow.com/questions/5877440/add-to-a-css-class-using-jquery) –

risposta

13

Si potrebbe creare un nuovo foglio di stile e aggiungere questo alla testa:

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

See Demo: http://jsfiddle.net/YenN4/2/

+0

+1 Molto più elegante. – iambriansreed

3

Demo: 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');​