【问题标题】:when fadeTo completes, fade divs back in with new color (rgba)当 fadeTo 完成时,用新颜色 (rgba) 淡入 div
【发布时间】:2012-03-22 14:28:27
【问题描述】:

我正在尝试自学一点 Javascript,并使用 jQuery 作为实验,制作了我随机间隔淡出的 div 集合!

我想确定每个 div 的不透明度何时为 0,以便我可以将它们淡入。

这是我目前所拥有的

/*
  author: Tim Down
  source: http://stackoverflow.com/a/4257739/1252748
*/
function hasClass(el, cssClass) {

    return el.className && new RegExp("(^|\\s)" + cssClass + "(\\s|$)").test(el.className);

}

function checkVisibility(id) {

    console.log(id);
}


function timeFunction(current, element) {

    var elementId = element.id;

    /*
      author: Remy Sharp
      source: http://twitter.com/#!/rem/status/15427387974
    */
    var color = '#' + (~~ (Math.random() * 16777215)).toString(16);
    var border = '#' + (~~ (Math.random() * 16777215)).toString(16);

    console.log(color);

    $('#' + elementId).css("backgroundColor", color);
    $('#' + elementId).css("border", "1px solid " + border);

}


function randomFromInterval(from, to, qty) {

    /*
      author: Francisc
      source: http://stackoverflow.com/a/7228322/1252748
    */

    var arr = [];

    for (var i=0; i <= qty; i++) {
        arr[i] = Math.floor(Math.random() * (to - from + 1) + from);
    }

    return arr;
}



function getDelayArray(qty) {

    var from = 100;
    var to   = 10000;
    var delayArray = randomFromInterval(from, to, qty);

    return delayArray;

}




function filterUndefinedRecordsInArray(arr) {

    /*
      author: vsync
      source: http://stackoverflow.com/a/2843625/1252748
    */


    //arr = arr.filter(function(){return true});
    arr = arr.filter(Number);

    return arr;
}



//remove non-numbers
function only_numbers(str) {

    //remove non-numbers

    /*
      author: csj
      source: http://stackoverflow.com/a/1862219/1252748
    */

    str = str.replace(/\D/g,'');
    return str;

}

function getColors() {


    var colors = randomFromInterval(0, 255, 3);

    var r = colors[0];
    var g = colors[1];
    var b = colors[2];

    //random alpha
    var a = (Math.random()).toFixed(2);

    var c = {

        r: r,
        g: g,
        b: b,
        a: a,

    }

    return c;
}

$(document).ready(function() {


    var grid      = "";
    var idCounter = 0;
    var rows      = 15;
    var columns   = 15;
    for (var g = 1; g <= rows; g++) {

        grid += "<div class='break'>";

        for (var i = 1; i <= columns; i++) {

            var c = getColors();
            var b = getColors();
            grid += "<div id='div_" + idCounter + "' class='fl pixel' style='background-color:rgba(" + c.r + "," + c.g + "," + c.b + "," + c.a + "); border:2px solid rgba(" + b.r + "," + b.g + "," + b.b + "," + b.a + ")'></div>";

            idCounter++
        }

        grid += "<div class='cb'></div>";
        grid += "</div>";

    }

    $('body').append(grid);

    //how to distribute the fading times
    var delayArray = getDelayArray(15);
    //console.log(delayArray);

    var idArray = [];

    var elements = document.getElementsByTagName("div");

    var current = 0;

    while (current <= (elements.length - 1)) {

        var currentElement = elements[current];

        if (hasClass(elements[current], "pixel")) {

            //get the divs' ids but remove the "div_" from the beginning
            var cleanCurrentElementId = only_numbers(currentElement.id);

            //an array of the ids of all the divs with the class 'pixel'
            //but it still gets some elements filled with undefined as
            //it increments outside the if ( hasClass ) loop
            //so below it must have these undefined elements removed
            idArray[current] = cleanCurrentElementId;
        }
        current++;
    }

    //an array of all the ids of the divs on the page that have the 'pixel' class
    var cleanIdArray = filterUndefinedRecordsInArray(idArray);

    //randomly pick a quantity from the above array (cleanIdArray)
    //set from / to / qty variables so that the randomly chosen numbers
    //are within the range of the availble divs
    var from   = 1;
    var to     = cleanIdArray.length;
    var qty    = 250;
    var idsToFade = randomFromInterval(from, to, qty);


    for (var fadeId in idsToFade) {

        var tempId = idsToFade[fadeId];

        var delay = getDelayArray(1);

        $('#div_' + tempId).fadeTo(delay[0], 0);

        //checkVisibility($('#div_' + tempId).attr('id'));

    }


});

演示: http://jsfiddle.net/loren_hibbard/dZtFu/

但我不知道如何确定每个 div 何时完成他的fadeTo

虽然,当我将它们淡入时,我想再次给它们一个随机的rgba 值;我知道 jquery .css 不支持。有谁知道我如何提供新的rgb 和不透明度值。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    整洁!

    fadeTo一个回调作为第三个参数:

    function giveRandomValue(){
        // Use your getColors() function here to set a new color and opacity
    
        // var color = ...;
        // $(this).css('background-color', color);
        // etc...
    }
    
    $('#div_' + tempId).fadeTo(delay[0], 0, giveRandomValue);
    

    Documentation at jquery.com

    【讨论】:

    • 谢谢!当我将其插入 (jsfiddle.net/loren_hibbard/jcyfG) 时,它可以完美运行!
    • 但是,当我尝试将正在更改的元素的 id 传递给它时,它会中断。 $('#div_' + tempId).fadeTo(delay[0], 0, giveRandomValue(tempId));这样,函数 giveRandomValue(div){ var now = new Date() console.log(div) ;控制台.log(现在); } 为每个褪色的 div 返回相同的确切时间戳,而在此之前,它们是连续的。 jsfiddle.net/loren_hibbard/BfQfz
    • 这不是你使用回调的方式;)你不能提供这样的参数,它只会接受要调用的函数的名称。然后将调用该函数,并将 this 设置为正在褪色的元素。在giveRandomValue 中,您将使用$(this) 来获取jquery 元素。无需直接处理 id。确实,你可以使用Rodolphe的randomDiv作为回调,只需将他的函数改为$(this).css({...
    • 根据您使用 Rodolphe 的代码更新的小提琴:jsfiddle.net/sM32J/2
    • 酷!不知道您不能将参数传递给回调函数。这是总是的事情吗?还是 jquery 的东西或所有编程语言的东西?有没有 no 方法给函数一个变量?此时,“this”和“$(this)”有什么区别? console.log(this) 和 console.log($(this)) 一样。再次感谢您的帮助!
    【解决方案2】:

    将您的 div 元素提供给 randomDiv 函数,它应该可以工作 :)

    function randomColor() {
      return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).toUpperCase();
    }
    
    function randomOpacity() {
      return Math.floor(Math.random() * 100) / 100;
    }
    
    function randomDiv(div) {
      $(div).css({
        'background-color': randomColor(),
        'opacity': randomOpacity()
      });
    }
    

    【讨论】:

    • 谢谢,两位!我仍然遇到回调部分的问题。这似乎总是给我带来麻烦。 Rodolphe,我在这里尝试了您的解决方案(jsfiddle.net/loren_hibbard/sM32J)。你能告诉我我做错了什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2012-11-20
    • 1970-01-01
    • 2014-04-25
    相关资源
    最近更新 更多