2012-09-18 19 views
6

Chcę utworzyć nowy styl, a nie tylko zmienić atrybut stylu elementu. Oto przykładowy kod do zademonstrowania problemu:Utwórz nowy (trwały) styl CSS w 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);​ 

W powyższym kodzie drugi element nie ma tego samego stylu co pierwszy. To, co chciałbym, to móc ustawić css na className dla wszystkich przyszłych elementów.

JSFiddle

+0

możliwe duplikat [ Dodaj do klasy css za pomocą JQuery] (http: // stackov erflow.com/questions/5877440/add-to-a-css-class-using-jquery) –

Odpowiedz

13

Można by utworzyć nowy arkusz stylów i dołączyć to do głowy:

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

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

+0

+1 Znacznie bardziej elegancko. – 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');​ 
Powiązane problemy