我见过很多使用Math.floor()和Math.random()的地方
如下所示
$('a.random-color').hover(function() { //mouseover
var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
$(this).animate({
'color': col,
'paddingLeft': '20px'
},1000);
},function() { //mouseout
$(this).animate({
'color': original,
'paddingLeft': '0'
},500);
});
});为什么使用Math.floor()和Math.random()
发布于 2011-12-20 13:02:44
Math.random会给出一个介于0(含)和1(不含)之间的浮点数。
乘以256将得到一个介于0(含)到256 (不含)之间的数字,但仍为浮点数。
取该数字的底数将得到一个介于0和255 (包括0和255)之间的整数。
它是从0到255的整数,用来构造像rgb(72,25,183)这样的RGB值。
发布于 2011-12-20 13:05:29
似乎需要一种随机的颜色--每个分量的随机数在0到255之间。
Math.random()在[0,1]上返回一个随机数(例如,它可能恰好是0或最多但不包括1)。
将该随机值乘以256后,得到范围[ 255.99,256 ]上的随机数(即,它可能是0256,但绝不是256)。就快到了,但还不完全是。
Math.floor()将数字向下舍入为最接近的整数,使结果成为所需的0,255上的整数。
发布于 2011-12-20 13:03:25
Math.floor将给出一个整数并去掉小数。
Math.random返回一个介于0和1之间的数字,因此与256相乘时将产生十进制数。这就是为什么要使用floor去掉小数,否则rgb值将不起作用。
https://stackoverflow.com/questions/8571010
复制相似问题