简体   繁体   English

onClick更改背景图片

[英]onClick change background image

How could I make my current script rotate between 3 defined colors or images to change out the body's background ? 如何使当前脚本在3种定义的颜色或图像之间旋转以改变身体的背景?

Currently I have this: http://jsfiddle.net/VgM3e/ 目前我有这个: http : //jsfiddle.net/VgM3e/

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



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

But I am having difficulty coming up with the logic to rotate between 3 defined colors or images. 但是我很难提出在3种定义的颜色或图像之间旋转的逻辑。 I appreciate any assistance. 感谢您的协助。

check my fiddle...if this is what you want http://jsfiddle.net/VgM3e/2/ 检查我的小提琴...如果这是您想要的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;
      }

   });
});

Something like this? 像这样吗

   $(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'}) }
  });
 });

There you go: 你去了:

$(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++ };
    });
});

All you need to do is make sure there are valid color strings in the colors array. 您需要做的就是确保颜色数组中有有效的颜色字符串。 If you wanted to do background images you would just change the colors to urls (in string format, of course) and change the .css() function as necessary. 如果要制作背景图像,则只需将颜色更改为url(当然是字符串格式),然后根据需要更改.css()函数。

try this one 试试这个

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/ http://jsfiddle.net/prollygeek/VgM3e/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM