【问题标题】:jQuery get random color from a given listjQuery从给定列表中获取随机颜色
【发布时间】:2012-02-23 18:05:27
【问题描述】:

我想为我拥有的淡入/淡出文本功能的文本设置随机颜色

功能(有效):

jQuery("div.custom_logo").ready(

    function(){

        //initial fade-in time (in milliseconds)
        var initialFadeIn = 1500;

        //interval between items (in milliseconds)
        var itemInterval = 2000;

        //cross-fade time (in milliseconds)
        var fadeTime = 500;

        //count number of items
        var numberOfItems = jQuery("div.custom_logo").children().length;

        //set current item
        var currentItem = 0;

        //show first item
        jQuery("div.custom_logo").children().eq(currentItem).fadeIn(initialFadeIn);

        //loop through the items
        var infiniteLoop = setInterval(function(){
            jQuery("div.custom_logo").children().eq(currentItem).fadeOut(fadeTime);

            if(currentItem == numberOfItems -1){
                currentItem = 0;
            }else{
                currentItem++;
            }
            jQuery("div.custom_logo").children().eq(currentItem).fadeIn(fadeTime);

        }, itemInterval);

    }

);

假设我想要颜色:

蓝色:#37fff5 绿色:#8cff04 橙色:#ffa018 粉红色:#f247f8

虽然我知道如何将颜色添加到给定的元素,但我不知道如何从上面列出的单色中选择随机颜色:

要更改淡入淡出的文本的颜色,我会

//show first item
jQuery("div.custom_logo").children().eq(currentItem).css('color', theRandomColor).fadeIn(initialFadeIn);

与

jQuery("div.custom_logo").children().eq(currentItem).css('color', **NEWRandomColor**).fadeIn(fadeTime);

谢谢,

【问题讨论】:

标签: jquery random


【解决方案1】:

我觉得这样最好

RandomColor = function() {
    colors = ['red', 'white', 'blue', 'green']
    return colors[Math.floor(Math.random()*colors.length)];
}

函数的返回将是颜色 示例:

a = 随机颜色(); console.log(a) // “蓝色”

【讨论】:

    【解决方案2】:
    RandomColor = function () {
        var _colors = ["#aaa", "#bbb", "#ccc", "red", "white"];
        this.getRandomColor = function() {
            var rnd = Math.floor(Math.random()*_colors .length);
            return _colors[rnd];
        }
    };
    
    (new RandomColor()).getRandomColor();
    

    【讨论】:

    • 最近在写Java还是什么?这可能是一个简单的函数。
    • 简单 fn :) ok: function a() { return ["#aaa", "#bbb", "#ccc", "red", "white"][parseInt(5*Math .random())] };
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 2016-01-11
    • 1970-01-01
    • 2017-10-06
    相关资源
    最近更新 更多