【问题标题】:quit loop on JS event退出 JS 事件的循环
【发布时间】:2011-01-30 06:13:40
【问题描述】:

所以我对我的 JS 有点生疏,但这是我的代码...... 基本上我有一个图像,在鼠标悬停时,它会在一个充满其他图像的隐藏 div 中循环...淡出,替换 src,然后淡入。效果很好。但是一旦它通过所有图像,我希望它重新开始并继续循环它们直到 mouseout 事件停止它。

我以为我可以从函数cycle_images($(current_image)); 中再次调用该函数,但这会导致浏览器崩溃,这是可以理解的。有什么好的方法可以做到这一点?

$.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 next_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});
  });
});

【问题讨论】:

  • 我建议不要使用 .each 中的所有图像,而是使用 var img = $('div.image div.all_images img:first') 并继续使用 var img = $(this).next() || $('div.image div.all_images img:first');(或类似的东西)。

标签: javascript jquery infinite-loop


【解决方案1】:

听起来您希望它在鼠标移出时重新循环并停止。

定义cycle_images()函数后,添加一个标志,repeatCycle

cycle_images.repeatCycle = true;

在cycle_images函数的最后,添加一个带超时的递归调用

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

然后在鼠标移出,

cycle_images.repeatCycle = false;

【讨论】:

  • 所以我用你的(布拉德的建议)完全修改了我的代码,但是我现在在停止循环器时遇到了问题!我的 mouseout 函数正在创建 image_cycler 函数的新实例,而不是设置该选项。我认为这段代码更干净,但我怎样才能打破鼠标悬停的循环?
  • 哎呀。错字。我的意思是“你的(和布拉德的建议)”。递归调用非常棒。
猜你喜欢
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-25
  • 2012-06-03
  • 1970-01-01
相关资源
最近更新 更多