我试图在用户单击单词时创建不同的颜色状态
我的HTML
<a href='#' class='click' id='2'>
word
</a>
<a href='#' class='click' id='3'>
second word
</a>
Run Code Online (Sandbox Code Playgroud)
我想根据id切换文本背景.
例如,当用户单击word- >将背景颜色更改为黄色时再次单击 - >橙色并再次单击 - >原始(白色和透明).这是两个州.
第二个例子当用户点击second word- >将背景颜色改为黄色再次点击 - >橙色,再次点击 - >绿色再次点击 - >红色再次点击 - >(白色和透明)这是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…..
}
})
Run Code Online (Sandbox Code Playgroud)
我试图弄清楚如何根据id而不是硬编码来切换颜色.任何人都可以帮我吗?非常感谢!
基本上,你可以设置一个全局颜色数组,然后在每个链接上设置一个数据属性,以及一个max属性,然后在每次单击时,背景颜色将跳转到下一个颜色,直到它达到最大值然后它重新开始循环.
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]);
})
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2378 次 |
| 最近记录: |