j查询随机图像推子

jQuery random image fader

本文关键字:图像 随机 查询      更新时间:2023-09-26

我有一个标题区域,它被划分为图像的块区域,这些图像绝对位于块内,并且高度和宽度都不同。

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

我希望这些图像随机淡出并更改为另一个随机图像,或者在单击时淡入淡出。我已经让它工作了,除了"设置超时"或"设置间隔"只触发一次。我需要它处于无限循环中。

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

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);
});
});

您需要在淡入淡出结束时再次调用 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);
});