几周前发现了这个网站,这是一个检查我们各种代码并学到很多东西的好地方!
我刚刚开始学习网络编程课程并且遇到了一些问题,我想我的知识。
目标:页面加载后,显示图片andy_black.jpg。两秒钟后,将图像源以及浏览器中的图像更改为名为 andy_white.jpg 的第二个图像。这将每 2 秒来回更改一次。
我查看了这篇文章: SetInterval 函数调用
(我也搜索了其他标签,使用标签 [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>