动态更改JavaScript或jQuery中的CSS规则 [英] Dynamically change CSS rules in JavaScript or jQuery

查看:28
本文介绍了动态更改JavaScript或jQuery中的CSS规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来更改文档中导入的样式表的CSS规则.所以我有一个外部样式表,里面有一些 class div 属性.我想使用JavaScript或jQuery更改规则之一.

I'm looking for a way to change the CSS rules of my stylesheet imported in the document. So I have an external stylesheet and some class and div attributes inside. I want to change one of the rules with JavaScript or jQuery.

这里是一个例子:

.red{
    color:red;
}

所以这个想法是用JavaScript做一些事情,HTML知道现在 color 是另一种这样的颜色:

So the idea is to do something in JavaScript and the HTML knows that now the color is another color like this:

.red{
    color:purple;
}

但是我希望以后通过追加的方式添加的每个元素都具有此规则.因此,如果我添加一个CSS类为 .red span ,则文本必须为紫色而不是红色.

But I want to have this rule for every element that I add in the future by the way of append. So if I add a span with the CSS class .red, the text has to be purple and not red.

我希望我说清楚了.

推荐答案

您的jQuery .css() 方法来做到这一点.

You jQuery .css() method to do that.

$('.red').css('color', 'purple');

对于多个规则:

$('.red').css({
    'color': 'purple',
    'font-size': '20px'
});

将来通过追加的方式将动态元素添加到DOM时,只需为这些元素提供一些 class id 并编写 CSS 将这些规则附加到上面之后,它们将应用于所有动态创建的元素.

When you add dynamic element in future to DOM by the way of append, just give those element some class or id and write CSS rules like above after appending them and they will applied for all dynamically created element.

在我看来,添加动态规则不是一个好的解决方案.可以加载一些外部 CSS 文件.

Add dynamic rules is not a good solution in my point of view. Instead of the you can load some external CSS file.

但是,如果您需要类似动态规则的添加方法,则:

But if you need something like dynamic rules add method then:

$('head').append(
  $('<style/>', {
    id: 'mystyle',
    html: '.red {color: purple }'
  })
);

以及将来使用:

$('#mystyle').append(' .someother { color: green; font-size: 13px } ');

这篇关于动态更改JavaScript或jQuery中的CSS规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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