Dynamically change CSS rules in JavaScript or jQuery

岁酱吖の 提交于 2021-02-07 04:46:53

问题


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.

Here is an example :

.red{
    color:red;
}

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;
}

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.

I hope I made it clear.


回答1:


You jQuery .css() method to do that.

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

For multiple rules:

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

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.

Working sample

Note

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 }'
  })
);

And for future use:

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

Working sample




回答2:


You can inject style declarations into the DOM.

$("head").append('<style>.red { color: purple }</style>');



回答3:


If you want to add a rule, instead of editing each element's style directly, you can use CSSStyleSheet.insertRule(). It takes two parameters: the rule as a string, and where to insert the rule.

Example from the above link:

// push a new rule onto the top of my stylesheet
myStyle.insertRule("#blanc { color: white }", 0);

In this case, myStyle is the .sheet member of a style element.

As far as I can tell, the style element must be inserted into the document before you can grab its sheet, and it can't be an external sheet. You can also grab a sheet from document.styleSheets, e.g.

var myStyle = document.styleSheets[1]; // Must not be a linked sheet.
myStyle.insertRule("#blanc { color: white }", 0);

Note: The page recommends modifying elements by changing their classes, instead of modifying the rules.



来源:https://stackoverflow.com/questions/11990089/dynamically-change-css-rules-in-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!