【问题标题】:jquery --Chnage the background color in cyclic orderjquery --循环改变背景颜色
【发布时间】:2012-09-04 15:13:36
【问题描述】:

我有一个背景颜色为红色的 div。单击此 div 背景颜色应按循环顺序更改.. 红色、绿色和灰色.. 循环应继续。

我不想使用任何 jquery 插件来实现这一点

请参考jsfiddle

【问题讨论】:

  • 好的,开始写代码,我们来帮你
  • 即使你不想使用 jQuery 插件,我认为 @Raynos 的这个 (stackoverflow.com/a/6051567/325742) 是一个很好的方法。

标签: javascript jquery html css jquery-ui


【解决方案1】:

DEMO

<div class="myDiv"></div>​

div {
  background: #3f3;
  height: 40px;
  width: 40px;    
}

var cur = 0;
var colors = ['#3f3', '#f33', '#33f', '#ff3'];

$('.myDiv').click(function() {
    cur = (cur + 1) % colors.length;
    $(this).css('background', colors[cur]);
});   ​

【讨论】:

    【解决方案2】:

    您可以使用data 来存储当前状态:

    var classes = ['red', 'blue', 'green', 'yellow']
    
    $('#box').click(function () {
        var box = $(this);
        var index = box.data('current-index') || 0;
        index++;
        if (index >= classes.length)
            index = 0;
        box.data('current-index', index);
    
        box.removeClass(classes.join(' '));
        box.addClass(classes[index]);
    });
    

    工作示例http://jsfiddle.net/jD6XK/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-16
      • 2016-05-24
      • 1970-01-01
      • 2011-09-08
      • 2018-07-08
      • 2013-11-21
      • 1970-01-01
      • 2012-04-02
      相关资源
      最近更新 更多