【问题标题】:How to dynamically change a class css styling?如何动态更改类 CSS 样式?
【发布时间】:2017-02-09 22:02:21
【问题描述】:

目标

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

  1. 动态更改 CSS 类的样式
  2. 向元素添加/删除类

问题

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

示例

也可以通过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>

结果:

【问题讨论】:

  • 好问题!我的查询:为什么css 在其中附加inline
  • css() 修改样式属性。因此,添加 what多少 类并不重要。它没有定义 rule,其中 propertyselector 相关联。
  • 我看到你标记了一个正确的答案。只是觉得离开这个会很好。
  • @PhilipVoronov 链接的问题与接受的答案完全相同... O.o

标签: javascript jquery html css


【解决方案1】:

更短的格式:

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

sn-p:

$("<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>

【讨论】:

  • 只有在没有样式标签影响正文中的元素时才有效。如果是这样,它会出现在头部的任何内容之后,因此仍然会覆盖您的新样式表!提示:尝试将以下内容添加为 html &lt;style&gt;.redclass{color: blue;font-size: 2em;font-weight: bold;}&lt;/style&gt; 中的最后一个元素——当然,这是一种不寻常且不太可能发生的情况——但仍然值得一提。 ;)
【解决方案2】:

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

他们基本上做到了这一点:

之前

.someClass
{
  color: red;
}

之后

.someClass
{
  color: red;
}

.someClass
{
  color: white;
}

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

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

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

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>

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 您可以在 1 行中执行相同操作:$("head").append('&lt;style&gt;.redclass{color: darkred;}&lt;/style&gt;');
    【解决方案4】:

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

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

    您应该在 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>

    【讨论】:

    • 是的,当它不起作用时,我想到了这个(.css() 以这种方式实现),我只是提到了我尝试过的。我的问题是如何做我想做的事?
    • 改变了答案。正确的方法是如上所述在样式表中创建一个类。与您的样式 javascript 的唯一交互应该是更改类,除非您正在做基于物理的动画。
    • 如果我想允许用户更改“主题”(例如表格单元格的颜色),同时页面可以在用户使用页面时动态添加这些单元格怎么办? ?
    • 公平点,这是非常具体的,不是问题。
    • 我试图将我的情况细化为纯问题以便更好地理解
    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 2017-07-18
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2014-04-13
    • 2018-09-27
    • 2015-09-25
    相关资源
    最近更新 更多