onClick更改背景图片

时间:2013-12-02 01:51:07

标签: javascript jquery html5

如何让我当前的脚本在3种定义的颜色或图像之间旋转以更改身体的背景?

目前我有这个: http://jsfiddle.net/VgM3e/

<button class="color">click to change color</button>



   $(document).ready(function(){
      $('body').on("click", function(){
         $(this).css({'background' : 'red'});
      });
   });

但我很难想出在3种定义的颜色或图像之间旋转的逻辑。我感谢任何协助。

4 个答案:

答案 0 :(得分:3)

检查我的小提琴...如果这是你想要的 http://jsfiddle.net/VgM3e/2/

 $(document).ready(function(){
  var rotate = 0;
  var colors = ["blue","red","green"];
  $('body').on("click", function(){

     $(this).css({'background' : colors[rotate]});
      rotate++;
      if(rotate >= 3){
      rotate = 0;
      }

   });
});

答案 1 :(得分:1)

这样的东西?

   $(document).ready(function(){
   var ex = 0;

  $('body').on("click", function(){
      ex = (ex+1)%3;
      if (ex == 0) { $(this).css({'background' : 'red'}) }
      else if (ex == 1) { $(this).css({'background' : 'green'}) }
      else { $(this).css({'background' : 'blue'}) }
  });
 });

答案 2 :(得分:1)

你去了:

$(document).ready(function(){
    var colors = ["red", "blue", "green"];
    var current = 0;
    $('body').on("click", function(){
        $(this).css({'background' : colors[current]});
        if (current >= colors.length - 1) {
            current = 0;
        }
        else { current++ };
    });
});

您需要做的就是确保colors数组中有有效的颜色字符串。如果你想做背景图像,你只需要将颜色更改为网址(当然是字符串格式),并根据需要更改.css()函数。

答案 3 :(得分:1)

尝试这个

i=0;
$(document).ready(function(){
      $('body').on("click", function(){
switch (i)
{
case 0:
         $(this).css({'background' : 'red'});
        break;

case 1:
         $(this).css({'background' : 'green'});
        break;

case 2:
         $(this).css({'background' : 'blue'});
        break;
}
i++;
if(i==3)i=0;
      });
   });

http://jsfiddle.net/prollygeek/VgM3e/3/

相关问题