更改现有的css属性,并通过删除或添加css元素来使用它

change existing css attribute and use it by removing or adding the css element

本文关键字:css 元素 添加 删除 属性      更新时间:2023-09-26

我有一个关于更改现有css属性的问题。我在html代码中使用Jquery。

我想知道如何更改现有的css类属性,并将更改后的类应用于其他元素。

谢谢你关心我的问题。

★css代码示例

.AccentColor{color:#fff;background:#000;}

★javascript

<script>
$(document).ready(function(){
$('.AccentColor').css('background','yellow');
$('#target').addClass('AccentColor');
});
</script>

★html

<p id="target"> still background color is #000, not yellow.</p>

您应该从传递给addClass函数的类名中删除点

$(selector).addClass("classname")

请确保使用了正确的类名。在您的情况下,AccentColor

解决问题的方法是简单地切换jquery函数的顺序:

<script>
$(document).ready(function(){
$('#target').addClass('AccentColor');
$('.AccentColor').css('background','yellow');
});
</script>

说明:

在操作css之前,必须先将类添加到目标中。事实上,如果将jquery选择器切换到#target而不是.AccentColor,代码将按预期工作。在这种情况下,您可以使用jquery链接轻松地重写它,以保持它更干净。

$('#target').addClass('AccentColor').css('background','yellow');

希望这能有所帮助。

您正在将css更改为所有不存在的类为"AccentColor"的元素。然后,您将一个类"Accent"添加到一个确实存在的元素中,但是类"Accept"没有在css中定义。试试这个:

$('#target').addClass('AccentColor'); //notice no dot "." is needed here.