2011-01-30 78 views
0

所以我是一个有点生疏与我的JS,但这里是我的代码... 基本上我通过一个隐藏的div全其它图像有一个图像,即鼠标悬停,它的周期...褪色它取代了src,然后渐渐消失,它效果很好。但一旦它通过所有的图像,我希望它重新开始并保持循环,直到mouseout事件停止它。退出环上JS事件

我想我可能只是再次从功能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}); 
    }); 
}); 
+0

我会建议不要使用.each中的所有图像,但使用`var img = $('div.image div.all_images img:first' )`并继续`var img = $(this).next()|| $('div.image div.all_images img:first');`(或类似的东西)。 – 2011-01-30 06:16:50

回答

0

这听起来像你想要它重新循环,并停止mouseout。

在定义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; 
+0

所以我完全修改我的代码与你的(布拉德的建议),但是我现在有问题停止循环仪!我的mouseout函数正在创建image_cycler函数的新实例,而不是设置该选项。我认为这段代码更清洁,但是我怎样才能在mouseout上打开循环? – brewster 2011-01-31 10:00:42