我试图在包含 2 个单词的 h1 上的 2 种颜色之间切换。 我为每个单词设置默认的 1 颜色,并尝试通过向它们添加一个类来切换它们,但似乎有些错误。
function myFunction() {
$("#id1").toggleClass("class1");
$("#id2").toggleClass("class2");
};
#id1 {
text-align: center;
color: blue;
}
.class1 {
color: grey;
}
#id2 {
text-align: center;
color: grey;
}
.class2 {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="id1"> <span id="id2">bla</span> bla</h1>
<button onclick="myFunction()">click</button>
有什么建议吗? LE:谢谢大家的回答!
最佳答案
尝试在你的两个类中引入!important
function myFunction() {
$("#id1").toggleClass("class1");
$("#id2").toggleClass("class2");
};
#id1 {
text-align: center;
color: blue;
}
.class1 {
color: grey !important;
}
#id2 {
text-align: center;
color: grey;
}
.class2 {
color: blue !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="id1"> <span id="id2">bla</span> bla</h1>
<button onclick="myFunction()">click</button>
关于jquery - 已解决 : How can I toggle between 2 colors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58950347/