颜色动画的 jQuery 数学 - 特定颜色范围

标签 jquery math animation colors

我使用这个数学来制作悬停时的背景颜色动画:

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)

也就是说,如果您想创建一个介于 100200 范围内的随机数,我们应该这样做

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 });
    });
});

示例: http://jsbin.com/iwovew

关于颜色动画的 jQuery 数学 - 特定颜色范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3845868/

相关文章:

android - Android AnimationSet 是否会覆盖子动画的持续时间和插值器?

javascript - jQuery scrollTop() 方法不起作用

javascript - 如何动态地将高度添加到包含响应图像的 div

math - 查找 3d 点到线段的距离

c++ - 使用正确的优化算法 C++ 查找 3D 空间中点之间的距离

c++ - 使用定点代替浮点的快速平方根求逆

ios - 为 CGAffineTransformMakeRotation Swift 设置旋转点

jquery 显示 div,停留几秒钟,然后以淡入淡出动画关闭

javascript - 将数据从 php 传递到 Jquery

jquery - ColdFusion 9、JSON 和 jQuery EasyUI