admin管理员组文章数量:1201993
I want to create a new style, not just alter the style attribute of an element. 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.
JSFiddle
I want to create a new style, not just alter the style attribute of an element. 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.
JSFiddle
Share Improve this question edited Sep 19, 2012 at 11:57 Danil Speransky 30.5k6 gold badges69 silver badges78 bronze badges asked Sep 18, 2012 at 14:36 DrahcirDrahcir 12k25 gold badges88 silver badges128 bronze badges 1- possible duplicate of Add to a css class using JQuery – Diodeus - James MacFarlane Commented Sep 18, 2012 at 14:38
2 Answers
Reset to default 19You 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/
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');
本文标签: javascriptCreate a new (permenant) CSS style in jQueryStack Overflow
版权声明:本文标题:javascript - Create a new (permenant) CSS style in jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738579409a2101070.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论