使用setInterval从数组更改背景图像,但只有两次

时间:2017-03-30 17:55:40

标签: javascript jquery loops jinja2 setinterval

目的

我尝试使用background-image: url

根据数组中的图像每四秒更改一次<div> setInterval
  • 阵列中最多可以有四个图像
  • 我遇到的问题是我需要循环数组两次,然后返回到数组中的第一个图像,然后停止setInterval.

我在

的地方

现在,背景图像仅在停止前切换一次。我应该提到我使用Jinja和一些JavaScript,但这两种语言在语法上包含相似之处。

scripts.js中

    $(function() {

        // Array of images
        var carouselImages = [

            // Returns a list containing a progression of integers
            // Similar to iterating over an array
            {% for n in range(1, coursePhotos) %}
                "{{ COPY.content.cdn_url }}/courses/{{course.slug}}/{{course.slug}}-{{n}}.jpg",
            {% endfor %}
        ];

        // The div of the background I want to change
        var carousel = $(".course__images");

        // Change the background image every four seconds
        var changeBackgroundImage = setInterval(function(){

            // Returns a list containing a progression of integers
            // Similar to iterating over an array
            {% for n in range(1, coursePhotos) %}
                carousel.css("background-image", "url({{ COPY.content.cdn_url }}/courses/{{course.slug}}/{{course.slug}}-{{n}}.jpg");
            {% endfor %}
        }, 4000);
    });

1 个答案:

答案 0 :(得分:2)

实施例

var images = [
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=one&w=100&h=100',
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=two&w=100&h=100',
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=three&w=100&h=100',
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=four&w=100&h=100'
];

var img = document.querySelector('#image');
var index = 0;
var iterations = 0;

var updateImage = function() {
  /* reset index to zero if current index is greater than number of images.
   * increment iterations variable since it means we've done one whole loop.
   */
  if (index >= images.length) {
    index = 0;
    iterations++;
  }

  // set the background image
  img.style.backgroundImage = 'url(' + images[index] + ')';

  /* clear interval (stop timer) when we've reached
   * the number of iterations allowed.
   */
  if (iterations >= 2) {
    clearInterval(interval);
  } else {
    /* increment current index in order to get next image
     * when this function gets called again.
     */
    index++;
  }
}

// update first image
updateImage();

// initiate timer
var interval = setInterval(updateImage, 4000);

JSFiddle演示:https://jsfiddle.net/3wayry32/1/