2012-07-06 62 views
0

我有一个标题区域被分成图像的块区域,这些图像绝对位于块内,并且都是不同的高度和宽度。jQuery随机图像推子

我有一个URL /随机图像?width = x & height = y & random = 34234它会生成随机图像以用于特定位置。

我希望这些图像随机淡出并更改为另一个随机图像,或淡入点击。我已经得到它的工作,除了“setTimeout”或“setInterval”只触发一次。我需要它在无限循环中。

这里是我的代码,任何想法:

jQuery(document).ready(function ($) { 

$('#main-image img').live('click', function() {  
    var $image = $(this), 
    width = $image.width(), 
    height = $image.height(), 
    random = Math.random();   

    $('<img src="/random-image?width='+width+'&height='+height+'&random='+random+'" />').hide().load(function() { 
     $(this) 
     .appendTo($image.parentsUntil('div.columns')) 
     .fadeIn('slow', function() { 
      $image.remove(); 
     }); 

    });   
}); 

$('#main-image img').each(function() { 
    var $image = $(this), 
    randVal = Math.round(5000 + Math.random()*(30000 - 5000)) ; 

    setTimeout(function() { 
     console.log($image.attr('src')); 
     $image.trigger('click'); 
    },randVal); 
}); 

}); 

回答

1

您需要在淡出结束时再次打电话给你的setTimeout函数。我能想到做到这一点的最简单的方法是命名您所使用的功能,然后从两个地方调用它,如下面的(完全未经测试)版本:

jQuery(document).ready(function ($) { 

var changeImage = function() { 
    var $image = $(this), 
    randVal = Math.round(5000 + Math.random()*(30000 - 5000)) ; 

    setTimeout(function() { 
     console.log($image.attr('src')); 
     $image.trigger('click'); 
    },randVal); 
}; 

$('#main-image img').live('click', function() {  
    var $image = $(this), 
    width = $image.width(), 
    height = $image.height(), 
    random = Math.random();   

    $('<img src="/random-image?width='+width+'&height='+height+'&random='+random+'" />').hide().load(function() { 
     var newImage = this; 
     $(this) 
     .appendTo($image.parentsUntil('div.columns')) 
     .fadeIn('slow', function() { 
      $image.remove(); 
      changeImage.call(newImage); 
     }); 

    });   
}); 

$('#main-image img').each(changeImage); 

}); 
+0

谢谢,我认为这是它,本周末脑冻结! – 2012-07-06 15:35:28