[英]Different randomized background image for multiple divs
How would I go about alternating the background with random images of each div with similar properties using javascript? 我如何使用javascript将背景与具有相似属性的每个div的随机图像交替? (Not all the divs should be the same image, though there may be overlaps if the image pool is small)
(并非所有div都应该是相同的图像,但如果图像池很小则可能存在重叠)
I have multiple divs with the same properties, in my case: 在我的情况下,我有多个具有相同属性的div:
<div class="background" id="bgimg"></div>
I also have a folder (images/) that has obj1.jpg, obj2.jpg ... obj5.jpg 我还有一个文件夹(images /),有obj1.jpg,obj2.jpg ... obj5.jpg
So far I have a javascript code: 到目前为止,我有一个JavaScript代码:
function bckg(){
var images = ['obj1.jpg', 'obj2.jpg', 'obj3.jpg', 'obj4.jpg', 'obj5.jpg'];
var div = document.querySelector('#bgimg');
div.style.backgroundImage = 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')';
}
However, not all divs end up with randomized images. 然而,并非所有div都以随机图像结束。 Rather only the first div shows a randomized image.
相反,只有第一个div显示随机图像。
How would I go about making each div have a randomized image? 我如何让每个div都有一个随机图像?
Thanks in advanced. 提前致谢。
document.querySelector
only selects the first item. document.querySelector
仅选择第一个项目。 ( https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector ) ( https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector )
Try document.querySelectorAll
( https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll ) and then loop through each of the items returned. 尝试
document.querySelectorAll
( https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll ),然后遍历返回的每个项目。
Also, as other people have mentioned, an ID is supposed to be unique. 此外,正如其他人所提到的,ID应该是唯一的。 If you want to have multiple divs with the same property, you should use matching classes.
如果要使用具有相同属性的多个div,则应使用匹配的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.