【问题标题】:JavaScript - for loop iteration delay for stacked imagesJavaScript - 堆叠图像的循环迭代延迟
【发布时间】:2013-02-26 14:27:02
【问题描述】:

我有一组图像,每张都有不同的 Z-index。顶部的“卡片”将依次排在 Z-index 最低的卡片下方(我们称之为“image1”),直到“image1”出现在其他卡片之上。这是用于动画的,但我无法让 for 循环以设定的时间进行迭代。我现在想在 1 秒内尝试 30 张图像。代码如下:


function placeImage(x) {
    var div = document.getElementById("div_picture_right");
    div.innerHTML = ""; // clear images

    for (counter=1;counter<=x;counter++) {
        var image=document.createElement("img");
        image.src="borboleta/Borboleta"+counter+".png";
        image.width="195";
        image.height="390";
        image.alt="borboleta"+counter;
        image.id="imagem"+counter;
        image.style.backgroundColor="rgb(255,255,255)"
        image.style.position="absolute";
        image.style.zIndex=counter;
        div.appendChild(image);
    }
};

var animaRight = function(x) {
        var imageArray = [];
        for (counter=1;counter<=x;counter++) {
            imageArray[counter-1] = document.getElementById("imagem"+counter);
        }
    function delayLoop(x) { 
        for (counter=imageArray.length;counter>1;counter--) {
            if (imageArray[counter-1].style.zIndex==counter) {
                imageArray[counter-1].style.zIndex-=counter;
                setTimeout("delayLoop()", 1000/x);
            }           
        }
    }
    delayLoop(x);
};

任何帮助将不胜感激!我尝试了一些 setTimeout 功能,但恐怕我做错了(可能是放置?)。如果您需要,我将使用我尝试过的内容来编辑代码。

【问题讨论】:

  • 如果没有您的尝试,很难猜出您的问题,但也许这个related question 会有所帮助?
  • 我马上编辑!问题是,我尝试了很多方法,所以我必须选择一种。

标签: javascript for-loop iteration z-index settimeout


【解决方案1】:

这是你想要的吗?

var animaRight = function(x) {
    var imageArray = [];
    for (counter=1;counter<=x;counter++) {
        imageArray.push(document.getElementById("imagem"+counter));
    }
    for (var i=0; i<x; i++) {
        (function(i) {
            setTimeout(function(){
                imageArray[i%imageArray.length].style.zIndex=i*-1
            }, i*1000);
        })(i);
    }
};

如果它做你想要的,我会解释更多。

【讨论】:

  • 很遗憾,它不起作用。以前,我可以让每张图片的 Z-index 发生变化。使用这段代码,它不会改变我想要的。虽然我会用你的推理来适应我所拥有的,看看它是否有效。顺便说一句,我可以做一些推荐的阅读,以便更好地使用它吗?我从阅读和分析代码开始,使用 w3schools 和自己编写代码。这是我的第一个项目,但我发现的书籍并没有涉及到这个主题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 2023-04-03
相关资源
最近更新 更多