【问题标题】:How to set up an array of images and loop through them individually如何设置图像数组并单独循环它们
【发布时间】:2014-12-16 07:37:39
【问题描述】:

对于更熟悉 javascript 的人来说,这可能是相当简单的任务。我想要一组图像,然后遍历它们以显示每个图像,每个图像之间有一定的时间间隔。

  1. 将图像存储在数组中: var anArray = [image1, image2, image] (我可以通过简单地将图像的 src 放入这样的数组中来将图像放入数组中吗?当我尝试将每个图像都视为字符串时。)
  2. 创建一个循环遍历数组中的每个图像并淡入每个图像: for (var i = 0; i
  3. 设置时间间隔:setInterval(functioin() {}, 1000);这样每张图片都会在 1 秒或之后显示几秒。

我知道我可以使用插件,但我正在尝试学习 javascript,所以我想避免走捷径(当然除了在这里寻求帮助的捷径!)

谢谢

【问题讨论】:

  • 显示您当前的代码?

标签: javascript arrays loops


【解决方案1】:
var img;
for(length)
{
  img[i]=new Image();
  img[i].src="src";
} 

//用于将图像存储为数组

var count=0;
var timerid = setInterval(function()
{
   //fade in image
   count++;
   if(count > length)clearInterval(timerId); 
}, 1000);

更好的选择是将所有图像添加到 image.onload 上的 DOM 中,并带有 display:none 标签,然后使用循环一个一个地淡入图像,

【讨论】:

  • 感谢您的快速回复并将其分解
  • 如果我已经在 html 中添加了图像,请将 display 设置为 none,循环看起来会如何淡入图像? for(var i = 0; i
【解决方案2】:

另一种选择是对计数器使用闭包。计数器最优雅地实现为闭包。

// Wrapping the code in a self envoking function prevents polluting the global namespace.
(function() {

    // The images array.
    var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];

    // The counter function using a closure.
    var add = (function() {
        // Setting the counter to the last image so it will start with the first image in the array.
        var counter = images.length - 1;
        return function() {
            // When the last image is shown reset the counter else increment the counter.
            if(counter === images.length - 1) {
                counter = 0;
            } else {
                counter+=1;
            }
            return counter;
        }
    })();

    // The function for changing the images.
    setInterval(
        function() {
            console.log(images[add()]);
        }
    , 1000);

})();

【讨论】:

    猜你喜欢
    • 2020-03-25
    • 2020-12-16
    • 2018-08-04
    • 2016-07-18
    • 2011-01-03
    • 2015-07-04
    • 2014-07-17
    • 1970-01-01
    • 2019-08-30
    相关资源
    最近更新 更多