在jQuery中创建新的(持久性)CSS样式 [英] Create a new (permenant) CSS style in jQuery

查看:81
本文介绍了在jQuery中创建新的(持久性)CSS样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一种新样式,而不仅仅是更改元素的样式属性.下面是一些示例代码来演示该问题:

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

在上面的代码中,第2个元素的样式与第1个元素的样式不同.我希望能够在所有将来的元素的className上设置css.

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

推荐答案

您可以创建一个新的样式表并将其附加到头部:

You could create a new stylesheet and append this to the head:

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

请参阅演示: http://jsfiddle.net/YenN4/2/

这篇关于在jQuery中创建新的(持久性)CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆