将图像添加到随机化的backstretch集 - jquery

时间:2017-11-16 09:04:12

标签: jquery

我正在使用backstretch将图像显示为站点主体上的背景,如下所示:

jQuery(document).ready(function($) {

  var images = [
    "/path/to/img1",
    "/path/to/img2",
    "/path/to/img3",
    "/path/to/img4",
    "/path/to/img5",
  ];

  function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    return array;
  }

  images = shuffle(images);

  $("body").backstretch([
    images[0],
    images[1],
    images[2],
    images[3],
    images[4],
  ],{
    duration:10000,
    fade:3000,
  });
});

我使用shuffle()来随机化图像数组中图像的顺序,这样当加载页面时会使用随机图像,然后以随机顺序进行更改。

我正在寻找的是一种能够将图像添加到阵列的方法。目前,backstretch函数使用已知的索引长度,但如果我再向图像中添加一个图像,我还需要在后伸的数组中添加另一个图像[index]。

有关如何解决此问题的任何想法?

非常感谢

1 个答案:

答案 0 :(得分:0)

我明白了。

在WordPress中(可能应该在前面提到过),我在排队脚本后使用wp_localize_script()函数。然后我可以将值作为数组传递。

wp_localize_script( 
    'script_handle', 
    'object_name_inside_script', 
    $array_of_values_to_pass_in 
);

现在我有一个可以使用的数组。