Javascript Changing Random Background Image Issue

和自甴很熟 提交于 2019-12-12 02:57:48

问题


I am on Rails 4, and finally got this javascript working. It changes randomly changes the background image every 10 seconds with a fadein fadeout effect.

The only issue is every so often, an image will only load halfway... then it will start to flash and and get crazy. It will continue to erratically flash from picture to picture until i refresh the page.

Does anyone know why this is happening? Maybe poorly written javascript? All of my pictures are located in public/assets.

home.html.erb:

<div id="imageDiv" class="imageContainer"></div>

  <script>
    var myImages = new Array("sushi.jpg", "pizza.jpg", "steak.jpg", "greens.jpg", "pancakes.jpg", "redbull.jpg", "coffeepow.jpg", "frenchfries.jpg", "tabs.jpg", "cigarettes.jpg", "noodles.jpg", "jelly.jpg", "pills2.jpg", "pills3.jpg", "gator.jpg", "needle.jpg", "tv.jpg", "cantop.jpg", "spices.jpg", "sliders.jpg", "fishoil.jpg", "chips.jpg", "cherries.jpg", "ciglighter.jpg", "eggs.jpg", "bakingsoda.jpg", "pasta.jpg", "beer.jpg", "champagne.jpg", "peppers.jpg");

    $(document).ready(function() {
        var random = myImages[Math.floor(Math.random() * myImages.length)];
        random = 'url(assets/' + random + ')';
        $('#imageDiv').css('background-image', random);

        setInterval(function() {
            SetImage();
        }, 10000);
    });

    function SetImage() {
        var random = myImages[Math.floor(Math.random() * myImages.length)];

        random = 'url(assets/' + random + ')';
        $('#imageDiv').fadeOut(900);

        setTimeout(function () {
            $('#imageDiv').css('background-image', random);
            $('#imageDiv').fadeIn(900);
        }, 900);
    }
  </script>

回答1:


I don't really want to get deep into your code, in two words: whatever is happening is happening because you have to wait for some actions to complete before they complete (such as animations) and you never want have timeouts within intervals.

This has to be helpful:

var images = ["http://i.imgur.com/xYDljlP.jpg",
          "http://i.imgur.com/f9MgLTO.jpg",
          "http://i.imgur.com/ECM9LKl.jpg"];


function setBackground() {
    var rand = Math.floor(Math.random() * images.length);
    $( "#imageDiv" ).fadeOut(300, function() {
      $( "#imageDiv" ).css("background", "url( " + images[rand] + " )");
      $( "#imageDiv" ).fadeIn(300, function() {
         setTimeout(setBackground, 3000);
      });
    });
}

setBackground();

Please see the fiddle: jsfiddle



来源:https://stackoverflow.com/questions/30854827/javascript-changing-random-background-image-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!