随机图像旋转的多个实例

Multiple instances of random image rotation

本文关键字:实例 图像 旋转 随机      更新时间:2023-09-26

我正在努力解决如何使id="cover__thumb"的所有图像实例在预定义的图像中随机旋转。

目前只有第一个id="cover__thumbs"会旋转,它对具有相同id的其他图像没有影响。

不会总是有4个图像,有时更多,有时更少。有并没有一个解决方案适用于任何具有此id的图像?

Fiddle

https://jsfiddle.net/bpLdkhg0/

JS-

function rotateImages()
{
    var thumbImages = new Array( );
    thumbImages[0] = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg";
    thumbImages[1] = "http://cdn.images.express.co.uk/img/dynamic/13/590x/magnolia-tree-630524.jpg";
    thumbImages[2] = "http://cdn.images.express.co.uk/img/dynamic/109/590x/Oak-tree-580618.jpg";
    var image = document.getElementById('thumb__cover');
    var randomImageIndex = Math.floor( Math.random( ) * thumbImages.length );
    image.src = thumbImages[randomImageIndex];
}
window.setInterval(rotateImages, 1000);

HTML

<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">

如果要同时选择多个DOM元素,请使用class属性:

HTML:

<img class="thumb__cover" ... />

JS:

var images = document.querySelectorAll(".thumb__cover");

var images = document.getElementsByClassName("thumb__cover");

现在,图像是一个nodeList,它可以具有任意数量的元素。要为每个项目设置src属性,您必须循环浏览列表中的项目:

for (var i = 0; i < images.length; i += 1) {
  var image = images[i];
  var randomImageIndex = Math.floor(Math.random() * thumbImages.length);
  image.src = thumbImages[randomImageIndex];
}

有关节点列表的详细信息:https://developer.mozilla.org/en/docs/Web/API/NodeList