假设我有一个充满图像来源网址的数组,例如:
var imgs = ['http://lorempizza.com/380/240',
'http://dummyimage.com/250/ffffff/000000',
'http://lorempixel.com/g/400/200/',
'http://lorempixel.com/g/400/200/sports/'];
如何获取所有这些图像并将其插入页面中的特定位置?说...
<div id="imageContainer"></div>
一种方法是遍历图像数组,img
为每个图像创建一个元素,将元素的src设置为数组中的当前图像源,然后将其附加到容器中。看起来像:
var imgs = ['http://lorempizza.com/380/240',
'http://dummyimage.com/250/ffffff/000000',
'http://lorempixel.com/g/400/200/',
'http://lorempixel.com/g/400/200/sports/'];
var container = document.getElementById('imageContainer');
for (var i = 0, j = imgs.length; i < j; i++) {
var img = document.createElement('img');
img.src = imgs[i]; // img[i] refers to the current URL.
container.appendChild(img);
}
但是,这并不是特别有效:
i
和j
变量相反,让我们使用documentFragment和JavaScript的forEach Array方法。
var imgs = ['http://lorempizza.com/380/240',
'http://dummyimage.com/250/ffffff/000000',
'http://lorempixel.com/g/400/200/',
'http://lorempixel.com/g/400/200/sports/'];
var container = document.getElementById('imageContainer');
var docFrag = document.createDocumentFragment();
imgs.forEach(function(url, index, originalArray) {
var img = document.createElement('img');
img.src = url;
docFrag.appendChild(img);
});
container.appendChild(docFrag);
这样我们可以:
然后只是为了确保您的新图像看起来不错,在混合中添加一些CSS:
#imageContainer img {
width: 20%;
height: auto;
}
am!这是一个小提琴
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句