【问题标题】:Random images load without repeat随机图像加载而不重复
【发布时间】:2016-06-23 03:13:12
【问题描述】:

您好,我发现一个脚本可以将图像一个接一个地加载到我的 div 元素中。一切正常,但我希望它加载不会在所有 images.length 的圆圈中重复的随机图像。

由于我在这方面完全是新手,所以我尝试做一些事情,但大多数时候我能够加载随机图像但无需重复检查。

如果可以的话,请帮忙。

提前谢谢大家!

<script src="js_vrt/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length));
var ist;
//Initial Background image setup
image.css('background-image', 'url(' + images[i++] + ')');
//Change image at regular intervals
setInterval(function() {

image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1500);
});
if (i == images.length)
  i = 0;
}, 5000);
});
</script>

【问题讨论】:

  • 尝试每次调用函数i == images.length
  • 对于我在末尾插入的随机性 -> if ( i== images.length) i=Math.floor((Math.random() * (images.length-1)) + 0); else i = Math.floor((Math.random() * (images.length)) + 0); 现在它会加载随机图像,但它不会进行“重复检查”所以问题是如何将这个集成到上面的脚本中重复检查'?

标签: javascript jquery image random repeat


【解决方案1】:

这是一个完整的对象,它接收一组图像 url,然后随机显示它们,直到全部显示。 cmets 应该非常具有解释性,但如果我解释得不够充分,请随时提出问题。这是fiddle

//Object using the Revealing Module pattern for private vars and functions
var ImageRotator = (function() {
  //holds the array that is passed in
  var images;
  // new shuffled array
  var displayImages;
  // The parent container that will hold the image
  var image = $("#imageContainer");
  // The template image element in the DOM
  var displayImg = $(".displayImg");
  var interval = null;

  //Initialize the rotator. Show the first image then set our interval
  function init(imgArr) {
    images = imgArr;
    // pass in our array and shuffle it randomly. Store this globally so
    // that we can access it in the future
    displayImages = shuffle(images);
    // Grab our last item, and remove it
    var firstImage = displayImages.pop();
    displayImage(firstImage);
    // Remove old image, and show the new one
    interval = setInterval(resetAndShow, 5000);
  }
    // If there are any images left in our shuffled image array then grab the one at the end and remove it.
  // If there is an image present in the Dom, then fade out clear our image
  // container and show the new image
  function resetAndShow() {
    // If there are images left in shuffled array...
    if (displayImages.length != 0) {
      var newImage = displayImages.pop();
      if (image.find("#currentImg")) {
        $("#currentImg").fadeOut(1500, function() {
          // Empty the image container so we don't have multiple images
          image.empty();
          displayImage(newImage);
        });
      }
    } else {
     // If there are no images left in the array then stop executing our interval.
      clearInterval(interval);
    }

  }
    // Show the image that has been passed. Set the id so that we can clear it in the future.
  function displayImage(newImage) {
    //Grab the image template from the DOM. NOTE: this could be stored in the code as well.
    var newImg = displayImg;
    newImg.attr("src", newImage);
    image.append(newImg);
    newImg.attr("id", "currentImg");
    newImg.fadeIn(1500);
  }
    // Randomly shuffle an array
  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;
  }

  return {
    init: init
  }
});
var imgArr = [
  "https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg",
  "https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg",
  "https://i.ytimg.com/vi/icqDxNab3Do/maxresdefault.jpg",
  "http://www.funny-animalpictures.com/media/content/items/images/funnycats0017_O.jpg",
  "https://i.ytimg.com/vi/OxgKvRvNd5o/maxresdefault.jpg"
]
// Create a new Rotator object
var imageRotator = ImageRotator();
imageRotator.init(imgArr);

【讨论】:

    【解决方案2】:

    你可以尝试让数组用 0 填充

    var points = new Array(0,0,0, 0) 
    //each one representing the state of each image
    //and after that you make the random thing 
    var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
    while (points[i]!=1){
    var image = $('#pozad');
    var i = Math.floor((Math.random() * images.length));
    var ist;
    }
    setInterval(function() {
    
    image.fadeOut(1500, function() {
    image.css('background-image', 'url(' + images[i++] + ')');
    points[i]=1;
    image.fadeIn(1500);
    });
    

    【讨论】:

      【解决方案3】:

      您可以使用下面答案中解释的随机播放方法。

      How can I shuffle an array?

      并获取数组中的第一个元素

      image.css('background-image', 'url(' + images[0] + ')');
      

      您可能会发现此方法存在问题,即在对数组进行洗牌后加载相同的图像。在这种情况下,我建议您将显示的最后一张图片的名称存储在一个变量中,并且在数组被打乱之前,只需测试第一个元素是否等于最后一张图片。

      var lastImageLoaded ='';
      
      setInterval(function() {
         shuffle(images);
         var imageUrl = images[0];
         if(lastImageLoaded !== ''){ // Handle the first load
            while(lastImageLoaded === images[0]){
                shuffle(images);
            }
         }
         lastImageLoaded = image;
         image.fadeOut(1500, function() {
            image.css('background-image', 'url(' + imageUrl + ')');
            image.fadeIn(1500);
      });
      

      【讨论】:

      • 感谢Fisher-Yates Shuffle的链接!我学到了一些新东西并解决了我的问题! :)
      猜你喜欢
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 2011-06-19
      • 2016-04-08
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多