在Javascript中使用循环创建和加载图像
Create and Load Images using a loop in Javascript
我很抱歉,但我是一个严格的新手。
请有人告诉我如何使用循环加载图像?
。重写以下类型的代码,以使用循环来自动化该过程。
function loadimages() {
pic00 = new Image;
pic00.src = "images/IMG_0019.jpg";
pic01 = new Image;
pic01.src = "images/IMG_0020.jpg";
pic02 = new Image;
pic02.src = "images/IMG_0021.jpg";
pic03 = new Image;
pic03.src = "images/IMG_0022.jpg";
pictures = new Array(4);
pictures[0] = pic00;
pictures[1] = pic01;
pictures[2] = pic02;
pictures[3] = pic03;
}
我看过许多描述类似事情的帖子,但我怕我太笨了,看不懂。感谢任何帮助。
对
这样做:
var URLs = [
"http://placehold.it/128x128.png/f00/400?text=Red",
"http://placehold.it/128x128.png/0f0/040?text=Green",
"http://placehold.it/128x128.png/00f/004?text=Blue",
"http://placehold.it/128x128.png/ff0/440?text=Yellow"
];
var imgs = URLs.map(function(URL) {
var img = new Image();
img.src = URL;
document.body.appendChild(img);
return img;
});
对于您的示例,您需要某种方法来知道每个图像路径/文件名是什么(因为它们不是IMG_001.jpg, 002.jpg等)。一种简单但技术含量低的方法是将所有文件名打包到一个数组中,作为我们的源信息:
//Pack the image filenames into an array using Array shorthand
var imageFiles = ['IMG_0019.jpg', 'IMG_0020.jpg', 'IMG_0021.jpg', 'IMG_0022.jpg'];
然后,循环遍历数组中的每个元素,并为每个元素创建一个图像元素。我们将创建image元素,并将其打包到最后的数组中:
//Loop over an array of filenames, and create an image for them, packing into an array:
var pictures = []; //Initialise an empty array
for (var i = 0, j = imageFiles.length; i < j; i++) {
var image = new Image; //This is a placeholder
image.src = 'images/' + imageFiles[i]; //Set the src attribute (imageFiles[i] is the current filename in the loop)
pictures.push(image); //Append the new image into the pictures array
}
//Show the result:
console.log(pictures);
这是为了易于理解而编写的代码,而不是为了提高效率。
for x in y
循环可能导致问题的原因。这里的for循环语法几乎是JS中数组循环的"经典香草"。
另外,如果你的图像文件名总是数字和顺序的,你可以利用这一点,但要"计算"它们,而不是预先存储它们。
让我们知道如果有什么你想要更多的细节!
真的很丑,但是你可以使用图像的onload
属性来运行一个javascript函数:
<img id="imgToLoad" onload="loadNextImage();" src="image1.png"/>
这个函数可以负责加载下一个图像:
function loadNextImage () {
document.getElementById( "imgToLoad" ).src = "image2.png";
}
相关文章:
- 如何创建带有插槽的vue js组件预加载程序
- DataTables-创建自定义分页样式(加载更多样式)
- 如何使用特定的javascript函数创建一个url,以便在加载页面时运行
- 要求创建空模块作为依赖项加载程序
- 懒惰加载:如何使用jquery创建懒惰加载html页面
- RequireJS正在加载angular应用程序,但没有't创建app.controller
- 如何在我的情况下创建加载脚本
- Firefox扩展开发:如何在内容脚本中创建一个全局函数,以便其他加载的脚本文件可以访问它
- 在新表单上使用JavaScript创建多个共享点项目,但将下一页加载延迟到全部创建
- 在页面加载时创建/设置活动的默认链接,但在单击其他链接时删除活动链接
- 创建 UI 加载程序时的引导程序
- 使用 FileReader 加载 CSV 以创建地图标记的 JS 对象 (地图 API)
- 在加载后创建的对象上使用 jQuery 选择器
- InnerHTML创建问题,没有't加载顺序正确,可能存在处理问题
- 创建加载时可见的预加载页面
- 如何在调用模型提取时在主干中创建加载屏幕
- 创建加载 d3.js 的浮动图像
- 如何为节点webkit创建加载屏幕
- 如何在我的情况下创建加载屏幕
- 如何创建加载弹出停留5秒