如何从一组颜色的单击中更改元素的颜色
假设我有一个称为太阳的矩形div。
我有4种为Div的颜色。
颜色分别为红色,绿色,蓝色和黄色。
初始颜色为红色。
我想要的是当用户单击矩形时,矩形的颜色应从红色变为绿色。再次单击时,将绿色为蓝色,因此在另一键点上,当用户再次点击时,蓝色到黄色和atlast,颜色应从黄色变为红色,并且循环应继续。我无法实现这种算法。
如果使用IF-Else树(尽管不是必需的),则应对答案表示赞赏。
Lets suppose I have a rectangular div called sun.
I have 4 colors for the div.
The colors are red, green, blue and yellow respectively.
The initial color is red.
What I want is when user clicks on the rectangle, the color of rectangle should change from red to green. When clicked again, green to blue, and thus on another click, blue to yellow and atlast when user clicks again the color should change from yellow to red and the cycle should continue. I can not implement such algorithm.
Answer is appreciated if if-else tree is used (although not necessary).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就像@bravo评论一样,您可以使用JavaScript数组,并与EventListener一起添加
它,但它。
Like @Bravo comment you can use javascript array and add with eventListener
It rought but that it.
如果其他答案无济于事,这是我在评论中提出的
简单数组和索引,并使用modulo操作员将“包装”到0的数组中的索引
增加的好处 - 无需全局变量
If the other answers don't help, here's what I was suggesting in the comment
a simple array and an index into the array that is "wrapped" to 0 using the modulo operator
Added benefit - NO global variables required
您的问题具有JS数组和索引检查的简单解决方案
your problem have simple solution with js arrays and index check