如何在同一个函数中动画最近创建的DOM元素?

How can I animate a recently created DOM element in the same function?

本文关键字:创建 DOM 元素 最近 动画 同一个 函数      更新时间:2023-09-26

我正在努力创建一个图片库,其中图像将通过逐步褪色的层一个在另一个顶部组成,以形成最终的图像。

我有许多这样的层,而不是加载它们到许多不同的<img>元素一次(这会减慢加载时间),我想开始与一个单一的<img id="base">,然后逐步添加图像元素与jQuery .after()方法,分配他们相关的来源,并逐渐淡出他们与延迟。

问题是我不能将动画附加到新创建的元素上,因为(我假设)它们还不存在于同一函数中。下面是我的代码:

<div id="gallery">
  <img id="base" src="image-1.jpg">
</div>
CSS

#base { 
    opacity: 0;
    }
.layers {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    }
JavaScript

$(document).ready(function () {
    $("#base").animate({opacity: 1}, 300); //fade in base
    for (var i = 1; i <= numberOfLayers; i++, gap += 300) {
        // create a new element
        $("#base").after("<img class='layers' src='" + imgName + ".png'>");
        // fade that new element in
        $("#gallery").children().eq(i).delay(gap).animate({opacity: '1'}, 300);
    }
}

请注意,为了更好地说明这一点,我修改了实际代码。我是JavaScript的新手,但我学得很快,所以如果你能告诉我我做错了什么,我应该采取什么解决方案,我会很感激。

编辑:我已经将我的代码包含在您的JSFiddle中(您所需要做的就是添加library- x.p jpg图像):http://jsfiddle.net/pgoevx03/


我试图以更干净/更灵活的方式复制代码的意图。如果我还能做些什么,请告诉我。

我并不是说这是最好的方法,但它应该足够容易理解和使用。

代码未经过测试,但应该可以正常工作。如果有任何编译错误,注释应该可以帮助您解决。

注意,我从HTML文件中删除了图库中的第一张图像(ID为"base")。它将以与其他部分相同的方式追加。

// Array storing all the images to append to the gallery
var galleryImages = [
    "image-1.jpg",
    "image-2.jpg",
    "image-3.jpg",
    "image-4.jpg",
    "image-5.jpg",
    "image-6.jpg",
    "image-7.jpg",
    "image-8.jpg",
    "image-9.jpg",
    "image-10.jpg"
];
// Index of the image about to be appended
var imgIndex = -1;
var baseID = "base";

$(document).ready(function() {
    // Start appending images
    appendAllImages();
});

// Append the images, one at a time, at the end of the gallery
function appendAllImages() {
    //Move to the next image
    imgIndex++;
    //We've reached the last image: stop appending
    if (imgIndex >= galleryImages.length) return;

    //Create image object
    var img = $("<img>", {
        src: galleryImages[imgIndex],
    });
    if (imgIndex === 0) { // It's the base!
        //Give the base ID to the first image
        img.attr("id", baseID);
        //Append the image object
        $("#gallery").append(img);

    } else { // It's a layer!
        //Give the base ID to the first image
        img.attr("class", "layers");
        //Append the image object
        $("#" + baseID).after(img);
    }
    //Fade in the image appended; append the next image once it's done fading in
    img.animate({
        opacity: 1,
    }, 300, appendAllImages);
}