本文介绍了从 CSS-Class 选择的 X 个 div 中显示随机 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have, on a homepage, X html div elements in one page, with X different classnames:

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

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

My goal is, to dislpay only one of these "divs" randomly, so when the page is refreshing, everytime a randomly different div is displayed. The rest should be hidden.it would be very nice if the same div was not shown twice in a row I think, i can't do this, only with css.

我手动可以做的是

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

所以在这种情况下显示 home-2.

So in this Case home-2 is displayed.

当然我希望用 javascript 自动完成,有人可以帮我吗?

Of course i want that automated with javascript, can someone please help me?

你会很不错!

推荐答案

您可以找到所有以类名 'home-' 开头的 div 元素,然后生成一个 0 到 X 之间的随机数并检查 localStorage 或 sessionStorage 以获取上次保存的 div 编号,如果新的随机数是前一个,则继续生成编号.

You can find all div elements that start with the class name 'home-', then generate a random number between 0 and X and check localStorage or sessionStorage for the last saved div number and keep generating numbers if the new random number was the previous.

见下文(脚本不会运行,因为 localStorage 在这里不起作用 - 在 SO 上):

See below (The script will not run because localStorage won't work here - on 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>

这篇关于从 CSS-Class 选择的 X 个 div 中显示随机 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 00:43