显示CSS类选择的X个div中的随机div



在主页上,一个页面中有X个htmldiv元素,具有X个不同的类名:

  • class="home-1">
  • class="home-2">
  • class="home-3">
  • class="home-4">
  • 等等

我的目标是,随机只显示其中一个"div",因此当刷新页面时,每次都会显示随机不同的div。其余的应该隐藏起来。如果同一个div没有连续显示两次,那就太好了我想,我不能这样做,只能用css。

我手动能做的是

.home-1 { display: none; }
.home-3 { display: none; }
.home-4 { display: none; }

因此,在本例中显示home-2。

我当然想用javascript实现自动化,有人能帮我吗?

你会很好的!

使用Math.random((并用您拥有的元素数量为其种子:

let els = document.querySelectorAll(".home")
let num = Math.floor(Math.random() * els.length)
els[num].style.display = "inline-block"
.home{display: none; padding: 15px}
.home-1{background-color: lightblue}
.home-2{background-color: yellow}
.home-3{background-color: pink}
.home-4{background-color: seagreen;color:#fff}
<div class="home home-1">1</div>
<div class="home home-2">2</div>
<div class="home home-3">3</div>
<div class="home home-4">4</div>

您可以随机找到该类,然后使用随机类隐藏除元素之外的所有元素:

var classList = Array.from(document.querySelectorAll('[class^=home-]')).map(el => el.className);
var random = classList[Math.floor(Math.random() * classList.length)];
document.querySelectorAll(`[class^=home-]:not(.${random})`).forEach(el => el.style.display = 'none');
<div class="home-1">home-1</div>
<div class="home-2">home-2</div>
<div class="home-3">home-3</div>
<div class="home-4">home-4</div>
<div class="home-5">home-5</div>

这个片段不会在stackerflow上运行,因为不允许您访问本地存储。但它在你的环境中应该很好用。

const elements = document.querySelectorAll('div[class^=home-]');
const lastIndex = Number(localStorage.getItem('lastElement'));
let randomIndex = lastIndex;
do {
randomIndex = Math.floor(Math.random() * elements.length);
} while (randomIndex === lastIndex);
const randomElement = elements[randomIndex];
randomElement.style.display = 'block';
localStorage.setItem('lastElement', randomIndex);
div[class^=home-] {
display: none;
}
<div class="home-1">home-1</div>
<div class="home-2">home-2</div>
<div class="home-3">home-3</div>
<div class="home-4">home-4</div>
<div class="home-5">home-5</div>

您可以找到所有以类名"home-"开头的div元素,然后生成一个0到X之间的随机数,并检查localStorage或sessionStorage中最后保存的div数,如果新的随机数是前一个,则继续生成数。

请参阅以下内容(脚本将不会运行,因为localStorage在SO上不起作用(:

function randomize() {
let divs = document.querySelectorAll('div[class^="home"]');
let length = divs.length;
let currDiv = localStorage.getItem("divActive");

rand = getNextRndm(currDiv, length);

for(var i=0; i<length; i++) {
if(i != rand) {
divs[i].style.display = "none";
} else {
divs[i].style.display = "block";
localStorage.setItem("divActive", rand);
}
}
}
function getNextRndm(currDiv, length) {
let rand = Math.floor(Math.random() * length);
if(currDiv !== null) {
while(rand == currDiv)
rand = Math.floor(Math.random() * length);
}
return rand;
}
randomize();
<div class="home-1">1st div</div>
<div class="home-2">2nd div</div>
<div class="home-3">3rd div</div>
<div class="home-4">4th div</div>

最新更新