我试图在用户单击单词时创建不同的颜色状态
我的html
<a href='#' class='click' id='2'>
word
</a>
<a href='#' class='click' id='3'>
second word
</a>
我想根据id切换文本背景。
例如,当用户单击word
时 -> 将背景颜色更改为黄色,再次单击 -> 橙色,然后再次单击 -> 原始(白色和透明)。这是 2 个州。
第二个示例,当用户单击第二个单词
-> 将背景颜色更改为黄色再次单击 -> 橙色,再次单击 -> 绿色并再次单击 -> 红色并再次单击 ->(白色和透明) )有 3 个州
颜色状态基于 id 属性。
我的代码就像
$('.click').click(function(){
var states = $(this).attr('id');
var classname = $(this).attr('class');
switch (classname){
case 'click':
$(this).attr('class', 'yellow');
$(this).css('background-color', 'yellow');
break;
case 'yellow':
$(this).attr('class', 'orange');
$(this).css('background-color', 'orange');
break;
case 'orange':
$(this).attr('class', 'red');
$(this).css('background-color', 'red');
break;
case 'red':
$(this).attr('class', 'click');
$(this).css('background-color', 'white');
break;
//add more if I have too…..
}
})
我试图弄清楚如何根据 id
切换颜色,而不是对其进行硬编码。谁能帮我解决这个问题吗?非常感谢!
最佳答案
基本上,您可以设置一个全局颜色数组,然后在每个链接上设置一个数据属性以及一个最大属性,然后每次单击时背景颜色都会跳到下一个颜色,直到达到最大值为止重新开始循环。
JS
var colors = ['white', 'yellow', 'orange', 'red'];
$('.click').click(function(){
var states = $(this).data('ci');
states++;
if(states > $(this).data('max'))
{
states = 0;
}
$(this).data('ci', states);
$(this).css('background-color', colors[states]);
})
HTML
<a href='#' class='click' data-ci='0' data-max="2">
word
</a>
<br>
<a href='#' class='click' data-ci='0' data-max="3">
second word
</a>
关于javascript - Jquery如何将文本背景更改为不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18259003/