我想在 jQuery 中单击按钮将标题从黄色更改为蓝色,然后再更改为黄色
$("#title2-button").click(function(){
if ($("#title2").css("color", "yellow")) {
$("#title2").removeClass("yellow");
$("#title2").addClass("blue");
} else {
$("#title2").css("color", "yellow");
}
});
#title2{
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id ="title2"> Weekends and Holidays Included</h2>
<button id="title2-button">Alter Second title</button>
最佳答案
您可以使用 .toggleClass()
如下所示。
这段代码基本上:
- 单击按钮时,它会“切换”类
blue
。这意味着如果#title2
有蓝色类,它会删除它。如果它没有类,它会添加它。!important
用于确保类blue
覆盖之前的黄色。 - 由于默认颜色为黄色,如果
toggleClass
移除该类,颜色将变回黄色。如果它添加类,则颜色变为蓝色(因为!important
在那里,颜色将是蓝色而不是黄色)。
$("#title2-button").click(function() {
$("#title2").toggleClass("blue");
});
#title2 {
text-align: center;
color: yellow;
}
.blue {
color: blue !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id ="title2"> Weekends and Holidays Included</h2>
<button id="title2-button">Alter Second title</button>
关于javascript - 如何切换按钮以将标题更改为不同的颜色并返回原始颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55682581/