你的代码中有几个功能问题:
- body标签的onload属性中的代码不正确关闭
- 代码内部changeBanner将始终执行所有if语句,永不执行图像周期
无论修复如何,您都可以使代码更清晰一些,从主体标记中删除内联脚本,并使用索引来修复if语句问题,以跟踪集中的当前图像。
假设你有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>
你并不需要使用body
的onload
属性。
使用window.onload
而不是您可以指定一个函数,该函数将在load
事件后自动调用,该事件在DOM准备就绪并加载所有图像之后。
最好你将所有的脚本代码放在一个单独的.js
文件中,并且只在HTML中包含对它的引用。不过,为了简单起见,我的确保持了目前的方法。
在你可以建立你的变量,然后启动间隔,与此类似的功能:
<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 - 固定的逻辑问题,并使用windows.onload()
“它不起作用'...关心这个更具描述性? *如何*它不起作用? – Arran
仔细检查你的语法。在调用'setInterval()'的时候,你至少错过了一个括号,你最好写'var img = [];'来创建你的数组。对于没有更具体的道歉,请致电 –
。它停留在第一张图片上。像弗雷德里克所说的,图像不会像我想要的那样改变 –