javascript 如何循环浏览一组图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15997497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:52:58  来源:igfitidea点击:

How do I cycle through a set of images?

javascript

提问by Timothy Coetzee

I'm trying to make a banner that cycles through 3 images using JavaScript.
Each image should be displayed for 10 seconds before changing.

我正在尝试使用 JavaScript 制作一个循环显示 3 个图像的横幅。
每个图像在更改前应显示 10 秒。

I wrote some code but it is not working. It stays stuck on the first image. The Image does not change as I want it to.

我写了一些代码,但它不起作用。它停留在第一张图像上。图像不会像我想要的那样改变。

Can you see anything in the code and point out my mistakes?

你能看到代码中的任何内容并指出我的错误吗?

Code as follows:

代码如下:

<script type="text/javascript">
    function changeBanner(){
        var img = new array

        img[0] = document.images[0].src
        img[1] = document.images[1].src
        img[2] = document.images[2].src

        var currentimg = img[0]

        if(currentimg == img[0]) {
            currentimg = img[1]
        }

        if(currentimg == img[1]) {
            currentimg = img[2]
        }
    }
</script>

HTML as follows:

HTML如下:

<body onload="var start=setInterval('changeBanner()', 10000;">
    <div id="wrapper">
        <div>
            <img src="budda.JPG" width="900px" height="300px" />
        </div>
...

回答by user2153497

var index = 0;

function changeBanner() {
    [].forEach.call(document.images, function(v, i) {
        document.images[i].hidden = i !== index
    });
    index = (index + 1) % document.images.length;
}
window.onload = function() {
    setInterval(changeBanner, 1000)
};

http://jsbin.com/emilef/2/edit

http://jsbin.com/emilef/2/edit

回答by Ed Heal

function changeBanner(){
var img = new array

img[0] = document.images[0].src
img[1] = document.images[1].src
img[2] = document.images[2].src

var currentimg = img[0]

Now currentimgis img[0]

现在currentimgimg[0]

if(currentimg == img[0]) {

This will be true currentimg = img[1] }

这将是真的 currentimg = img[1] }

Now currentImghas the value img[1]

现在currentImg有了价值img[1]

if(currentimg == img[1]) {

This will be true as well

这也将是真的

    currentimg = img[2]
}

currentImghas the value of img[2]

currentImg具有以下价值 img[2]

}

}

Now lets though away the value of currentImg

现在让我们忽略的价值 currentImg

You need to 1) sort out the logic 2) set a certain DOM object to this new value.

您需要 1) 理清逻辑 2) 将某个 DOM 对象设置为这个新值。

回答by Nope

Your code has several functional issues:

您的代码有几个功能问题:

  • The code in the onload attribute of the body tag was not closed correctly
  • The code inside changeBanner will always execute all if statements, never progressing with the image cycle
  • body标签的onload属性中的代码没有正确关闭
  • changeBanner 中的代码将始终执行所有 if 语句,永远不会随着图像循环进行

Regardless of the fixes you can make the code a little cleaner, remove in-line scripts form the body tag and fix the if statement issue by using an index to track the current image in the set.

无论修复如何,您都可以使代码更简洁,从 body 标记中删除内嵌脚本,并通过使用索引跟踪集合中的当前图像来修复 if 语句问题。

Assuming you have HTML like yours, with 3 images all starting of hidden:

假设您有像您这样的 HTML,其中 3 个图像均以以下开头hidden

<body>
    <div id="wrapper">
        <div>
            <img src="http://placehold.it/100x150" width="300px" height="150px" hidden />
            <img src="http://placehold.it/200x250" width="300px" height="150px" hidden />
            <img src="http://placehold.it/300x350" width="300px" height="150px" hidden />
        </div>
    </div>
</body>

You don't need to use the onloadattribute of the body.

你并不需要使用onload的属性body

Using window.onloadinstead you can assign a function which will automatically be called after the loadevent, which is after the DOM is ready and all images are loaded.

使用window.onload而不是您可以指定将自动被调用函数后的load事件,这是在DOM就绪后,所有图像都加载。

Preferably you would have all your script code inside a separate .jsfile and only include the reference to it in your HTML. However, I did stay close to your current approach for simplicity.

最好将所有脚本代码放在一个单独的.js文件中,并且只在 HTML 中包含对它的引用。但是,为了简单起见,我确实接近您当前的方法。

Within that function you can set-up your variables and then start the interval, similar to this:

在该函数中,您可以设置变量,然后开始间隔,类似于:

<script type="text/javascript">
    var currentImageIndex = -1,
        maxImageIndex = 0,
        images = [],
        changeInterval = 1500;

    // prepares relevant variables to cycle throguh images
    var setUp = function() {
        images = document.images;
        maxImageIndex = images.length;
        currentImageIndex = 0;
    };

    // changes the banner currently being displayed
    var changeBanner = function() {
        var i;

        // either re-set the index to 0 if the max length was reached or increase the index by 1
        currentImageIndex = (currentImageIndex >= maxImageIndex - 1) ? 0 : currentImageIndex += 1;

        for (i = 0; i < maxImageIndex; i += 1) {
            images[i].hidden = (i !== currentImageIndex);
        }
    };

    // a function which is triggered following the `load` event
    window.onload = function() {
        setUp();

        images[currentImageIndex].hidden = false; // show the first banner image;

        setInterval(changeBanner, changeInterval); // following a delay, keep changing the banner image by the specified interval
    };
</script>


DEMO- Fixing the logical issues and using windows.onload()

演示- 修复逻辑问题并使用windows.onload()



回答by Ikrom

Check this out in console ;)

在控制台中检查一下;)

var imgs=document.images;
function changeBanner(){
    var firstImgSrc = imgs[0].src + "";
    for(var i=0;i<imgs.length-1;i++){
        imgs[i].src=imgs[i+1].src+"";
    }
    imgs[imgs.length-1].src=firstImgSrc; //replace last image src with first one
}
var interval = setInterval(changeBanner, 5000);

回答by Sujal

The setInterval('changeBanner()', 10000;in your code is not closed properly, it has missing ")" after 10000. It should be:

setInterval('changeBanner()', 10000;你的代码无法正常关闭,它缺少“)” 10000后,它应该是:

setInterval('changeBanner()', 10000);

Also, the setInterval function will only be called when the body is loaded. So just add the function in your JavaScript file instead and link it to the html. Like this:

此外, setInterval 函数只会在加载主体时调用。因此,只需在 JavaScript 文件中添加该函数并将其链接到 html。像这样:

<script type="text/javascript">
function changeBanner(){
    var img = new array

    img[0] = document.images[0].src
    img[1] = document.images[1].src
    img[2] = document.images[2].src

    var currentimg = img[0]

    if(currentimg == img[0]) {
        currentimg = img[1]
    }

    if(currentimg == img[1]) {
        currentimg = img[2]
    }
}

  setInterval('changeBanner()', 10000);
</script>