setInterval()更改图像

时间:2013-08-25 20:35:39

标签: javascript image function setinterval

几个星期后发现这个网站,这是一个非常好的地方来检查我们的 各种代码,学到很多!!

我刚刚开始参加网络编程课程,并且遇到了一些问题,我想知道这些问题。

目标:加载页面时,显示图像andy_black.jpg。两秒钟后,将图像源和浏览器中的图像更改为名为andy_white.jpg的第二个图像。这将每2秒来回变换一次。

我查看了这篇文章: SetInterval function calls

(我也搜索了其他标签[javascript] [function]和“setinterval”这个词,但大多数人都使用jQuery,我的意图是不使用任何jQuery,毕竟这是一个JavaScript实验)

在我读它之前非常有帮助我的代码要长得多,而且函数没有在setInterval()函数中调用。

所以这里是一些代码: 建议? 谢谢大家,喜欢它:)。

 <img id="img_to_flip" src="pic_src"
        height="100"
        width="100"
         />

            <script type="text/javascript">
                var i = 1;

                function change_pic() {
                    i + 1;
                    if (i == 5) {
                        i = 1;
                    }
                    //I suspect the computer will read i as 5 for some
                    //tiny amount of time before reverting back to 1
                    //which I suspect could cause a further problem, but
                    //is it the source of the current issue?

                    if (i == 1 || i == 2) {
                        document.getElementById('img_to_flip').src = "andy_black.jpg";
                    }
                    else {
                        document.getElementById('img_to_flip').src = "andy_white.jpg";
                    }
                }
                var pic_src = setInterval(change_pic, 2000);
    </script>

1 个答案:

答案 0 :(得分:1)

您忘记将新值重新分配给i

使用:

i = i + 1;

++i;

另外,当你只有两个州时,为什么算到五?拥有自动重置计数器的常见范例是使用模数算术:

i = (i + 1) % 2;

保证i只有01的值。

FWIW,这是另一种编写适用于任意数量图像的整个功能的方法 - 只需填充pics数组:

(function() {     // function expression closure to contain variables
    var i = 0;
    var pics = [ "andy_white.jpg", "andy_black.jpg" ];
    var el = document.getElementById('img_to_flip');  // el doesn't change
    function toggle() {
        el.src = pics[i];           // set the image
        i = (i + 1) % pics.length;  // update the counter
    }
    setInterval(toggle, 2000);
})();             // invoke the function expression
相关问题