在 javascript 中循环浏览图像数组
Loop through array of images in javascript
>我正在尝试循环浏览图像数组,但似乎无法通过图像 2。
当最后一个图像通过时,数组也应该循环回 1...
var WorkArray = new Array('work/01.png', 'work/02.png', 'work/03.png', 'work/04.png');
var nelements = WorkArray.length;
preload_image_object = new Image();
var i = 0;
for(i=0; i<=nelements; i++) {
preload_image_object.src = WorkArray[i];
}
function cC() {
var nelements = WorkArray.length;
var i = 0;
for(i=0; i<=nelements; i++) {
nelements = WorkArray[i];
}
document.getElementById("work").style.backgroundImage="url('"+WorkArray[i]+"')";
}
您可以保存当前文件并使用模以循环方式运行。
它看起来像这样:
var WorkArray = new Array('work/01.png', 'work/02.png', 'work/03.png', 'work/04.png');
var currentImage = 0
function nextImage(){
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage="url('"+WorkArray[currentImage]+"')";
}
你正在用循环的当前元素覆盖 nelements:
nelements = WorkArray[i];
以下内容应该可以修复您的循环:
var WorkArray = new Array('work/01.png', 'work/02.png', 'work/03.png', 'work/04.png');
var preload_image_object = new Image();
/* Lets get rid of `nelements`, as its just confusing. Get the length here.
* If, for performace reasons you want to use elements, the best way is to reverse
* aka for(var i = WorkArray.length-1; i >= 0 ; i--)
* Also, its simpler to declare the var in your for-loop itself instead of outside of it.
*/
for(var i = 0; i <= WorkArray.length; i++){
preload_image_object.src = WorkArray[i];
}
此外,为了简化起见,背景图像的应用也可以在 for 循环中完成,并且可以通过一些空格和省略url()
内的'
来使其看起来更干净:
document.getElementById("work").style.backgroundImage = "url(" + WorkArray[i] + ")";
相关文章:
- 使用图像数组列表的simplegallary.js显示适合桌面屏幕的图像
- Javascript图像数组预加载速度和从内存中删除
- 将图像数组访问到动态表中
- Javascript图像数组
- JavaScript 在删除预上传图像时不清除图像数组
- 访问标记图标的图像数组元素
- 使用javascript/jquery获取具有图像数组的对象中的所有图像
- 如何将图像数组应用于Meteor.js中的模板辅助对象
- 如何创建图像数组作为链接
- 循环遍历图像数组并将其显示到HTML页面
- 打乱图像数组jquery
- 来自 flickr 的图像数组未按预期顺序显示
- 将图像数组从一个窗口传递到另一个窗口,并在javascript的新窗口中显示图像
- 使用 javascript 从图像数组中更改 img 标签 src.骰子游戏
- 将图像数组放入表中 - Javascript
- 加载带有 onload 的图像数组,如何限制将它们绘制到画布
- 如何自动循环浏览图像数组
- JavaScript:图像数组
- Javascript图像数组问题
- 在HTML5中使用JavaScript实现图像数组的拖放