我想创建一个新样式,而不仅仅是改变元素的样式属性。下面是一些示例代码来演示该问题:
//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);
在上面的代码中,第二个元素与第一个元素的样式不同。我想要的是能够为所有 future 元素在 className 上设置 css。
最佳答案
您可以创建一个新的样式表并将其附加到头部:
$("<style type='text/css'> .blue{ background-color:blue;} </style>").appendTo("head");
关于javascript - 在 jQuery 中创建一个新的(永久的)CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12479215/