0

好的,标题可能听起来很简单(也许确实如此),但我不知道如何显示数组中的值,不仅仅是对它们做一个而是把它们慢慢地放在网站上,很好影响...

像这个Twitter 小部件,但来自一个数组(可能等待 2 秒,然后从数组中抛出另一个值)?

我的数组包含另一个数组,有 4 个值,是否可以显示前 2 个值,等待大约 2 秒,然后显示最后 2 个值?现在,当最后两个值(从上一个数组)出来时,再等 2 秒,然后显示下一个数组(同样有四个值,首先显示 2,等待 2 秒,然后显示下一个 2,依此类推.. .)

4

2 回答 2

4

动画函数,如fadeIn()使用 jQuery FX 队列,因此您可以.delay()在调用链中使用来延迟这些函数的调用。在以下示例中,每秒显示一个元素。

var data = ['foo', 'bar', 'foobar', 'moo', 'meow', 'xxx'];
var list = $('ul');
$.each(data, function(i, value) {
    $('<li/>', { text: value }).hide().appendTo(list).delay(i * 1000).fadeIn();
});

演示:http: //jsfiddle.net/ThiefMaster/frW8s/

于 2012-04-25T20:10:08.033 回答
4

您可以使用setInterval或链接的一系列setTimeout. 我更喜欢后者,它看起来像这样:

function showValues(a, delay) {
    var index = 0;

    if (a.length !== 0) {
        // If you want a delay before the first one:
        setTimeout(showValue, delay);

        // Alternately, if you want to show the first right away
        // showValue();
    }

    // Function to show one value
    function showValue() {
        // Get the value
        var value = a[index++];

        /* ...show the value however you see fit... */

        // Schedule next display, if any
        if (index < a.length) {
            // Schedule next run
            setTimeout(showValue, delay);
        }
    }
}

用法:

showValues(["value1", "value2", /* etc. */, 2000); 2000 = two seconds

实例| 资源

于 2012-04-25T20:08:52.917 回答