开发者

quit loop on JS event

开发者 https://www.devze.com 2023-02-07 06:15 出处:网络
so im a little rusty with my JS, but here is my code... basically i have an image, that on mouseover, it cycles through a hidden div full of other images... fading it out, replacing the src, and fadin

so im a little rusty with my JS, but here is my code... basically i have an image, that on mouseover, it cycles through a hidden div full of other images... fading it out, replacing the src, and fading back in. it works great. but once it gets through all the images, i want it to start back over and keep looping through them until the mouseout event stops it.

i thought i could just call the function again from within the function cycle_images($(current_image));, but that leads to the browser freaking out, understandably. what is a good method to accomplish this?

$.fn.image_cycler = function(options){
  // default configuration properties
  var defaults = {
    fade_delay:     150,
    image_duration: 1500,
    repeatCycle:    true,
  };
  var options = $.extend(defaults, options);

  this.each(function(){
    var product     = $(this);
    var image       = $('div.image>a.product_link>img', product);
    var description = $('div.image>div.description', product);
    var all_images  = $('div.all_images', product);
    var nex开发者_JAVA百科t_image  = ($(all_images).find('img[src="' + $(image).attr('src') + '"]').next('img').attr('src')) ? $(all_images).find('img[src="' + $(image).attr('src') + '"]').next('img') : $(all_images).children('img').first();;

    // mouseover
    image.fadeOut(options.fade_delay, function(){
      image.attr('src', next_image.attr('src'));
      image.fadeIn(options.fade_delay);
    });
    if (options.repeatCycle){
      var loop = function() {
        product.image_cycler();
      }
      setTimeout(loop,options.image_duration);
    }
  });
};


$(document).ready(function() {
  $('div.product').hover(function(){
    $(this).image_cycler();
  }, function(){
    $(this).image_cycler({repeatCycle: false});
  });
});


It sounds like you want it to re-cycle and stop on mouseout.

After you define the cycle_images() function, add a flag, repeatCycle

cycle_images.repeatCycle = true;

At the end of the cycle_images function, add a recursive call with a timeout

if (this.repeatCycle) {
   var f = function() {
      return cycle_images.apply(this, [$current_image]);
   }
   setTimeout(f,50);
}

Then in mouseout,

cycle_images.repeatCycle = false;
0

精彩评论

暂无评论...
验证码 换一张
取 消