我有一个关于更改现有css属性的问题。 我在我的html代码中使用Jquery。
我想知道如何更改existsng 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>
答案 0 :(得分:1)
您应该从传递给addClass函数的类名中删除点
$(selector).addClass("classname")
确保您使用正确的类名。在您的情况下AccentColor
答案 1 :(得分:0)
您正在使用“AccentColor”类将css更改为所有元素,这些元素不存在。然后你将一个“Accent”类添加到一个确实存在的元素中,但是你的css中没有定义“Accent”类。试试这个:
$('#target').addClass('AccentColor'); //notice no dot "." is needed here.
答案 2 :(得分:0)
解决问题的方法是简单地切换jquery函数的顺序:
<script>
$(document).ready(function(){
$('#target').addClass('AccentColor');
$('.AccentColor').css('background','yellow');
});
</script>
说明:
在操作css之前,必须先将类添加到目标中。实际上,如果将jquery选择器切换到#target而不是.AccentColor,代码将按照您的预期运行。在这种情况下,您可以使用jquery链接轻松地重写它以使其更清洁。
$('#target').addClass('AccentColor').css('background','yellow');
希望这有帮助。