简体   繁体   中英

Jquery Animation - looping divs

Hey folks I'm having an issue with looping these divs.

When the first div leaves the screen I want it to jump back to the beginning of the screen and start looping again. Here is the jsfiddle .

I also have this function that I think should work, but it's not doing anything/I'm doing something wrong haha.

var boxes = $('#inner>div');
var speeds = [
0.5, 0.5, 0.35, 0.45, 0.46, 0.55, 0.5, 0.5
];

function update() {
  var width = $('#wrapper').width;

  // update boxes
  for (var i = 0; i < boxes.length; i++) {
    var box = boxes[i];
    var speed = speeds[i];

    box.left -= speed;

    if (box.left < -box.width) {
      cloud.left = width;
    }
  };
  window.setTimeout(update, 2000);
};

You will want your timer to run faster than once every 2000ms, I changed that to run every 20ms. This solution is based on using position: absolute; and changing the left property of your divs.

Some performance improvements you can make here is to store the widths of the divs and the width of the window so you don't have to recalculate those values every loop.

If you want to up the speed of the divs you can make the timer faster (more cpu load) or you can increase the values in the speed array (no big performance hit, might not look as smooth)

var boxes = $('#inner>div');
var speeds = [
0.5, 0.5, 0.35, 0.45, 0.46, 0.55, 0.5, 0.5
];

function update() {
  var width = $('#wrapper').width;

  // update boxes
  for (var i = 0; i < boxes.length; i++) {
    var box = $(boxes[i]);
    var speed = speeds[i];
    var leftPos = box.position().left;
    box.css({left: leftPos + speed});

    if (leftPos + box.width() > $(window).width()) {
      box.css({left: 0});
    }
  };
  window.setTimeout(update, 20);
};

$('#inner>div').each(function(i){
    $(this).css('top', i * 50);
});

update();

Fiddle: https://jsfiddle.net/u160Lg3h/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM