0

这是一个很小的 ​​js 文件,从某个地方抓取,在 wordpress 中用于使缩略图在页面加载时淡入淡出。

(function($) {
    $('.featured-thumbnail').each(function(i) {
        $(this).delay((i++) * 380).fadeTo(1000, 1); })
})(jQuery);

我想为 i 添加随机性。

问题是:在哪里使用 Math.random?我也应该使用 Math.floor 吗?我需要总 i 吗?似乎没有必要。

学习缓慢的 jQuery 新手。

4

1 回答 1

0

听起来您希望缩略图以随机顺序淡入。如果你对这些淡入淡出重叠没意见,你可以说:

(function($) {
    var len = $('.featured-thumbnail').length;

    $('.featured-thumbnail').each(function(i) {
    $(this).delay(Math.floor( Math.random() * 380 * len)).fadeTo(1000, 1); })
})(jQuery);

否则,您可以从列表中选择随机元素,并按照与原始元素相同的时间表将它们淡入:

(function($) {
  // jQuery selectors return array-LIKE objects,
  // but not actual arrays. We need a real array.
  //
  var items = $.makeArray( $('.featured-thumbnail') );
  var i = 0;

  while (items.length > 0)
  {
    // pick a random index within our array
    //
    var idx = Math.floor( Math.random() * items.length );

    // grab that item, remove it from the array.
    // splice() returns an array, so grab the first (only)
    // element from that array. splice() removes the
    // selected element(s) from the original array
    //
    var selected = items.splice(idx, 1)[0]; 

    // delay and fade in as before
    //
    $(selected).delay(i++ * 380).fadeTo(1000, 1);
  }
})(jQuery);
于 2014-08-04T17:29:03.033 回答