我使用这个数学来制作悬停时的背景颜色动画:
var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
它产生随机的 RGB 颜色。确实非常好,但我正在寻找不同的东西。
有谁知道一个好的数学,我可以用它来获得仅在特定颜色范围之外的随机颜色,例如在红色范围之外或在绿色范围之外?
感谢任何帮助。
@Avinash,这是我现在使用的完整代码。我怎样才能包含您的解决方案?
$(document).ready(function () {
//bg color animation
original = $('.item,.main-menu-button').css('background-color');
$('.item,.main-menu-button').hover(function () { //mouseover
var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; //random hover color
$(this).stop().animate({
'backgroundColor': col
}, 1000);
}, function () { //mouseout
$(this).stop().animate({
'backgroundColor': '#111'
}, 500); //original color as in css
});
});
它不起作用。我最好保持原样。感谢大家的帮助。
最佳答案
要生成一个范围内的随机数,我们需要做一些事情
minValue + random Number * (maxValue - minValue)
也就是说,如果您想创建一个介于 100 到 200 范围内的随机数,我们应该这样做
var rand = 100 + Math.floor(Math.random() * (200 - 100));
给出 100 到 200 之间的随机数
使用这个基本规则,我们可以从给定范围生成随机颜色
var range = [{0 : 150,1 : 200}, {0 : 200,1 : 230},{0 : 10,1 : 20}];
function rgb() {
var color ='rgb(';
for(var i = 0; i< 3; i++) {
color += rand(range[i]['0'], range[i]['1']) + ',';
}
return color.replace(/\,$/,')')
}
function rand(min, max) {
return min + Math.floor(Math.random() * (max - min));
}
alert(rgb());
试试这个代码 http://jsbin.com/tuday
编辑:
$(function() {
var cache = $('#hover').css('background-color');
$('#hover').hover(function() {
$(this).css({'background-color' : rgb() });
},function() {
$(this).css({'background-color' : cache });
});
});
关于颜色动画的 jQuery 数学 - 特定颜色范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3845868/