javascript – 每次刷新随机交换三种颜色

我有三个班,有三种不同的颜色.

如何在每次访问页面时随机交换背景颜色?

Fiddle

.projects{background:#99c6c3;}  
.other-things{background:#d3d3d3;}
.about {background:#eedd8d;}    

我试着用这个js:

var bgcolorlist=new Array("#99c6c3", "#d3d3d3", "#eedd8d")
$(".projects").css("background-color",bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]);

但我不希望两种颜色相同.

最佳答案
Updated fiddle

您可以从bgcolorlist中选择随机颜色然后使用splice()将其删除,以便下次不会选中它:

var bgcolorlist=new Array("#99c6c3", "#d3d3d3", "#eedd8d");
var elements=new Array(".projects", ".about", ".other-things");

for(var i=0;i<elements.length;i++){
  var random = Math.floor(Math.random()*bgcolorlist.length);
  $(elements[i]).css("background-color",bgcolorlist[random]);

  bgcolorlist.splice(random, 1); //remove selected color from array
}
body {font-size:21px; font-family:arial;}
.projects{text-align:center; line-height:100vh;background:#99c6c3;	overflow-x: hidden;width: 33%;float:left; height: 100vh;}	
.other-things{text-align:center; line-height:100vh;background:#d3d3d3;overflow-x: hidden;width: 33%;float:left; height: 100vh;}
.about {text-align:center; line-height:100vh;background: #eedd8d;	overflow-x: hidden;width: 33%;float:left; height: 100vh;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="projects">ONE</div>
<div class="other-things">TWO</div>
<div class="about">THREE</div>
点赞