简体   繁体   中英

Random select value in array and next apply to jQuery function

I have this function that returns a random color, but I want to apply it to jQuery .animate() function.

How can I do that?

var colors = ["rgb(120,25,25)", "rgb(50,100,130)", "rgb(30,95,45)", "rgb(55,30,90)"];
function randomBackground() {
   return colors[Math.floor(Math.random() * messages.length)];
}
$("#menu").animate({background: randomBackground()});

You could do:

var colors = ["rgb(120,25,25)", "rgb(50,100,130)", "rgb(30,95,45)", "rgb(55,30,90)"];
function randomBackground() {
   return colors[Math.floor(Math.random() * colors.length)];
   //use colors.length, not messages.length
}

var bgcolor = randomBackground();
$("#menu").animate({background: bgcolor });

sorry for you but if you read the jQuery documentation :

All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

that meens you cannot do the background color change using animate()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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