jquery - 多个图像淡入/淡出

标签 jquery

我有大约 20 张不同的图像,我想在 4 个框中淡入淡出。我需要它从图像列表中随机选择一个图像并显示它。

框示例 photo1、photo2、photo3、photo4 是它们的名称。它们需要根据其绝对定位而单独命名。

<div id="photo1">
    <img src="images/photo.jpg" width="300" height="300" />
    <img src="images/photo2.jpg" width="300" height="300" />
    <img src="images/photo3.jpg" width="300" height="300" />
    <img src="images/photo4.jpg" width="300" height="300" />
    <img src="images/photo5.jpg" width="300" height="300" />
</div>

jquery 到目前为止

<script type="text/javascript">

//generate random number
var randomnumber=Math.floor(Math.random()*$("#photo1").children().length);
$(function() {
    //hide all the images (if not already done)
    $("#photo1 > img").hide();

    //set timeout for image to appear (set at 500ms)
    setTimeout(function(){
       //fade in the random index of the image collection
       $("#photo1 > img:eq(" + randomnumber + ")").fadeIn();
    }, 500);       
});
</script>

最佳答案

我重构了你的代码:

$(function() {
    // match all divs with ID starting with 'photo'
    $("div[id^=photo] > img").hide();
    setTimeout(function(){
       $("div[id^=photo]").each(function() {
           var rand = Math.floor(Math.random() * $(this).children().length);
           $(this).find('img:eq(' + rand + ')').fadeIn();
       });
    }, 500);       
});

参见http://api.jquery.com/attribute-starts-with-selector/

关于jquery - 多个图像淡入/淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4279385/

相关文章:

jquery - 如何用jQuery检测IE7?

javascript - AngularJS 1.2.0-rc.2 与 1.2.0 元素绑定(bind)

javascript - jQuery "blinking highlight"对 div 的影响?

javascript - jQuery - 如何检查页面上可用的 javascript?

javascript - 有没有办法添加一个 javascript 按钮来删除添加的图表

javascript - 使用比例缩小屏幕

javascript - 势不可挡的addEventListener

javascript - IE+jQuery+Ajax+XHTML : HTML getting clipped after . html() 或 .innerHTML

javascript - 如何在 jQuery 中将 .done 或 .complete 与 .toggle 一起使用

jquery - 简单的 JQuery 逻辑