繁体   English   中英

如何以随机顺序显示 JavaScript 数组中的图像

[英]How to display images from a JavaScript array in random order

我试图显示图像列表,但每次页面刷新时,图像顺序都会随机更改,但类名不同的除外。 我写了这段代码,但它给了我一个重复的图像。

我想要三样东西:

  1. 显示所有没有重复的图像。

  2. 每次刷新页面时给它们随机顺序。

  3. 具有不同类名的那个不会改变位置。

    .ppl{ 宽度:250px; }
     var images = [], index = 0; images[0] = "<img class='ppl pos' src='images/1.jpg' >"; images[1] = "<img class='ppl pos' src='images/2.jpg' >"; images[2] = "<img class='ppl pos' src='images/3.jpg' >"; images[3] = "<img class='ppl n-pos' src='images/g.jpg' >"; images[4] = "<img class='ppl pos' src='images/4.jpg' >"; function myFunction() { for (var i = 0; i < images.length; i++) { index = Math.floor(Math.random() * images.length); document.write(images[index]); } } debugger; myFunction(); </script>

 const images = [ 'images/1.jpg', 'images/2.jpg', 'images/3.jpg', 'images/g.jpg', 'images/4.jpg' ] const root = document.querySelector('#root') const shuffle = ([...array]) => { let currentIndex = array.length let temporaryValue let randomIndex // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex) currentIndex -= 1 // And swap it with the current element. temporaryValue = array[currentIndex] array[currentIndex] = array[randomIndex] array[randomIndex] = temporaryValue } return array } const shuffledImages = shuffle(images) shuffledImages.forEach(src => { const image = document.createElement('img') image.src = src image.alt = src image.classList.add('ppl') image.classList.add('pos') root.appendChild(image) })
 .ppl { width: 250px; }
 <div id="root"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM