【问题标题】:Change background image randomly in several divs with JS用JS在几个div中随机改变背景图片
【发布时间】:2015-09-26 18:36:58
【问题描述】:

我需要每隔 3000 毫秒(带有淡入/淡出效果)在几个 div 中随机更改背景图像

  1. 我有 4 个 div,每个 div 都有背景图片
  2. 所有图像都来自一个数组

我该怎么做?

这是我的小提琴:

http://jsfiddle.net/vol4ikman/brrmkwp7/9/

var images = [
    "http://placehold.it/100x100",
    "http://lorempixel/100/100",
    "http://lorempixel/100/100",
    "http://lorempixel/100/100",
    "http://lorempixel/100/100",
    "http://lorempixel/100/100",
    "http://lorempixel/100/100",
    "http://lorempixel/100/100",
    "http://lorempixel/100/100"
];
.images_wrapper {
    width:600px;
    position:relative;
    margin: 0 auto;
    min-height:300px;
    background:silver;
    padding:20px;
}
.images_wrapper > div {
    width:100px;
    height:100px;
    overflow:hidden;
    position:relative;
    margin:10px;
    background-color:#FFF;
    border:1px solid #000;
    border-radius:50%;
}
<div class="images_wrapper">
    <div class="image-holder image-1"></div>
    <div class="image-holder image-2"></div>
    <div class="image-holder image-3"></div>
    <div class="image-holder image-4"></div>
</div>

【问题讨论】:

标签: javascript jquery html css slideshow


【解决方案1】:

这里是关于如何做到这一点的基本想法。有时间我会补充细节的。

var images = [
    "http://dummyimage.com/100x100/100/fff",
    "http://dummyimage.com/100x100/304/fff",
    "http://dummyimage.com/100x100/508/fff",
    "http://dummyimage.com/100x100/70B/fff",
    "http://dummyimage.com/100x100/90F/fff",
    "http://dummyimage.com/100x100/AA0/fff",
    "http://dummyimage.com/100x100/CB0/fff",
    "http://dummyimage.com/100x100/EC0/fff"
];
//A function to shuffle the images
function shuffle(o) {
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}
//Get a reference to the divs
var $divs = $(".images_wrapper > div");
//A self executing function
(function randomBackground() {

    //Make an array of length = $divs.length, which is nothing but $divs.length random images form the images array;
    var randomImages = shuffle(images).slice(0, $divs.length);
    //Cycle thru the divs
    var done;
    $divs.animate({
        opacity: .2
    },{
        start: function() {
            done = 0;
        },
        progress: function(p, n1, n2) {
            console.log(n1)
            if (!done && n1 > .7) {
                $divs.each(function(idx) {
                    //Set the background
                    $(this).css({
                        'background-image': 'url(' + randomImages[idx] + ')'
                    });
                });
                done = 1;
            }
        },
        complete: function() {
            $divs.animate({
                opacity: 1
            }, 400, function() {
            });
        }
    });
    //Repeat the function
    setTimeout(randomBackground, 3000);
}());

这里是a demo 的完整代码。

【讨论】:

    【解决方案2】:

    你可以试试这个例子:

    var images = ['http://www.placekitten.com/250/300','http://www.placekitten.com/260/300','http://www.placekitten.com/260/310'];
        var i = 0;
        var allDivs = [];
    function changeBackground() {
        allDivs = $(".hexagon-in2").each(function(){       
            setBG($(this),1000);
        });      
    }
    
    function setBG(div, time){
        var timeVar;
        clearTimeout(timeVar);
    
        if( div == undefined){
            return;   
        }
        div.css('background-image', function() {
            if (i >= images.length) {
                i=0;
            }
            return 'url(' + images[i++] + ')';      
       });
    
        timeVar = setTimeout(setTimer, time);    
    }
    
    
    function getRandomInt (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    function setTimer(){
        var imageIndex = getRandomInt(0,allDivs.length);
        setBG($(allDivs[imageIndex]),3000);  
    }
    
    $(function(){          
        changeBackground();        
    });
    

    DEMO

    【讨论】:

      【解决方案3】:

      首先,您应该使用setInterval 函数来获取时间循环。之后,您应该在每次迭代时从数组中选择一个图像。可以通过使用随机键从images 数组中调用一个元素来完成。要获得随机数,您应该使用:Math.random() 方法。请记住,它返回一个浮点数,而不是整数,因此您还应该进行转换。

      这里是updated fiddle。

       var images = [
          "http://placehold.it/100x100",
          "http://lorempixel/100/100",
          "http://lorempixel/100/100",
          "http://lorempixel/100/100",
          "http://lorempixel/100/100",
          "http://lorempixel/100/100",
          "http://lorempixel/100/100",
          "http://lorempixel/100/100",
          "http://lorempixel/100/100"
      ];
      
      var setInerval = setInterval(function() {
          $.each($(".image-holder"), function(key, element) {             
              $(element).css(
                  'background', 
                  'url(' + images[Math.random(0, iamges.length)] + ')' 
              );
          });
      }, 3000);
      
      function getRandomInt(min, max)
      {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }
      

      【讨论】:

        【解决方案4】:

        这是编辑后的有效代码:http://jsfiddle.net/brrmkwp7/17/

        var images = [
        "https://www.video2brain.com/en/images_dynam/product_class_external_product/jquery.png",
        "http://apigee.com/docs/sites/docs/files/icon_policy_javaScript.jpg"
        ];
        
        var divs = ["image-1", "image-2", "image-3", "image-4"];
        
        
        
        function setImages() {
        
            var image;
        
            for (var index = 0; index < divs.length; index++) {
                image = 'url(' + images[Math.floor(Math.random()*images.length)]  + ')';
                $("#" + divs[index]).css("background-image", image);
            }
        }
        
        setImages();
        var setInerval = setInterval(setImages, 3000);
        

        【讨论】:

          【解决方案5】:

          基本上,您需要做的是获取一个介于零和数组长度之间的随机数,并使用该索引从数组中选择图像,然后使用 jquery css() 函数将其设置为 div。使用 each() 在 div 之间进行迭代。将其设为函数并使用setInterval() 函数重复调用它。

          var images = [
              "http://dummyimage.com/100x100/100/fff",
              "http://dummyimage.com/100x100/304/fff",
              "http://dummyimage.com/100x100/508/fff",
              "http://dummyimage.com/100x100/70B/fff",
              "http://dummyimage.com/100x100/90F/fff",
              "http://dummyimage.com/100x100/AA0/fff",
              "http://dummyimage.com/100x100/CB0/fff",
              "http://dummyimage.com/100x100/EC0/fff"];
          min = 0;
          max = images.length - 1;
          $(document).ready(function () {
              randomImages();
          	setInterval(randomImages, 3000);
          });
          randomImages = function () {
              $('.image-holder').each(function () {
                  var number = getRandomArbitrary(min, max);
                  $(this).css('background-image', 'url(' + images[number] + ')')
              })
          }
          
          getRandomArbitrary = function (min, max) {
              return Math.floor(Math.random() * (max - min + 1)) + min;
          }
          .images_wrapper {
              width:600px;
              position:relative;
              margin: 0 auto;
              min-height:300px;
              background:silver;
              padding:20px;
          }
          .images_wrapper > div {
              width:100px;
              height:100px;
              overflow:hidden;
              position:relative;
              margin:10px;
              background-color:#FFF;
              border:1px solid #000;
              border-radius:50%;
          }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          <div class="images_wrapper">
              <div class="image-holder image-1"></div>
              <div class="image-holder image-2"></div>
              <div class="image-holder image-3"></div>
              <div class="image-holder image-4"></div>
          </div>

          【讨论】:

            猜你喜欢
            • 2017-10-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-02-02
            • 1970-01-01
            • 2021-06-02
            • 2017-06-21
            • 1970-01-01
            相关资源
            最近更新 更多