Javascript 如何动态更改类 css 样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39806536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:54:47  来源:igfitidea点击:

How to dynamically change a class css styling?

javascriptjqueryhtmlcss

提问by Philip Voronov

Goal

目标

In my program I want to do both things with jquery/javascript:

在我的程序中,我想用 jquery/javascript 做这两件事:

  1. Change styling of css classes dynamically
  2. Add/remove classes to elements
  1. 动态更改 css 类的样式
  2. 向元素添加/删除类

Problem

问题

To do the first thing I use $(".className").css()method, but it changes style only for those elements that alreadyhave classNameclass, i.e. if I lateradd classNameto an element its style won't be new. How can I solve this?

做第一件事我使用$(".className").css()方法,但它只为那些已经className类的元素改变样式,即如果我稍后添加className到一个元素,它的样式不会是新的。我该如何解决这个问题?

Example

例子

See it also at jsfiddle.

另请参阅jsfiddle

$("p").addClass("redclass");
$(".redclass").css("color", "darkRed");
$("span").addClass("redclass");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>

Result:

结果:

enter image description here

在此处输入图片说明

回答by gaetanoM

A more shorten format:

更短的格式:

$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');

The snippet:

片段:

$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');


$("p").addClass("redclass");

$("span").addClass("redclass");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>

回答by enhzflep

While other (working) answers have been supplied, they don't actually answer your question - namely, they don't changethe specified css class, but instead overrideit by adding another rule later in the document.

虽然提供了其他(工作)答案,但它们实际上并没有回答您的问题 - 即,它们不会更改指定的 css 类,而是通过在文档后面添加另一条规则来覆盖它。

They achieve this, basically:

他们实现了这一点,基本上:

Before

.someClass
{
  color: red;
}

After

.someClass
{
  color: red;
}

.someClass
{
  color: white;
}

When in many cases, a better option would see the color attribute of the existingrule altered.

在许多情况下,更好的选择是更改现有规则的颜色属性。

Well, as it turns out - the browser maintains a collection of style-sheets, style-sheet rules and attributes of said rules. We may prefer instead, to find the existing rule and alter it. (We would certainly prefer a method that performed error checking over the one I present!)

好吧,事实证明 - 浏览器维护了一组样式表、样式表规则和所述规则的属性。相反,我们可能更愿意找到现有规则并对其进行更改。(我们当然更喜欢一种执行错误检查的方法而不是我提出的方法!)

The first console msg comes from the 1 instance of a #coordsrule. The next three come from the 3 instances of the .thatrule

第一个控制台消息来自#coords规则的 1 个实例。接下来的三个来自.that规则的 3 个实例

function byId(id){return document.getElementById(id)}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded(evt)
{
 byId('goBtn').addEventListener('click', onGoBtnClicked, false);
}

function onGoBtnClicked(evt)
{
 alterExistingCSSRuleAttrib('#coords', 'background-color', 'blue');
 alterExistingCSSRuleAttrib('.that', 'color', 'red');
}

// useful for HtmlCollection, NodeList, String types (array-like types)
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need

function alterExistingCSSRuleAttrib(selectorText, tgtAttribName, newValue)
{
 var styleSheets = document.styleSheets;
 forEach(styleSheets, styleSheetFunc);

 function styleSheetFunc(CSSStyleSheet)
 {
  forEach(CSSStyleSheet.cssRules, cssRuleFunc);
 }

 function cssRuleFunc(rule)
 {
  if (selectorText.indexOf(rule.selectorText) != -1)
  forEach(rule.style, cssRuleAttributeFunc);

  function cssRuleAttributeFunc(attribName)
  {
   if (attribName == tgtAttribName)
            {
    rule.style[attribName] = newValue;
                console.log('attribute replaced');
            }
  }
 }
}
#coords
{
    font-size: 0.75em;
 width: 10em;
 background-color: red;
}
.that
{
 color: blue;
}
<style>.that{color: green;font-size: 3em;font-weight: bold;}</style>

<button id='goBtn'>Change css rules</button>
 <div id='coords' class='that'>Test div</div>

<style>.that{color: blue;font-size: 2em;font-weight: bold;}</style>

回答by Alec von Barnekow

@synthet1c has described the problem. My solution is:

@synthet1c 已经描述了这个问题。我的解决办法是:

$("head").append('<style></style>');
var element = $("head").children(':last');
element.html('.redclass{color: darkred;}');

回答by synthet1c

What you are having issue with is that when you use the jQuery selector $('.redclass').css('color', 'darkRed')you are getting all the elements that currently have that class and using javascript to loop over the collection and set the style property.

您遇到的问题是,当您使用 jQuery 选择器时,$('.redclass').css('color', 'darkRed')您将获取当前具有该类的所有元素,并使用 javascript 遍历集合并设置样式属性。

You then set the class on the span after. Which was not included in the collection at the time of setting the color

然后在之后的跨度上设置类。设置颜色时未包含在集合中

You should set the class in your css file so it is distributed to all elements that have that class

您应该在 css 文件中设置该类,以便将其分发给所有具有该类的元素

console.log($('.redclass').length)
$("p").addClass("redclass");
console.log($('.redclass').length)
// $(".redclass").css("color", "darkRed");
$("span").addClass("redclass");
console.log($('.redclass').length)
.redclass {
  color: darkRed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>