js Realizes Simple Random Color Instance Code of Roll Call Device

  • 2021-08-28 07:14:00
  • OfStack

js Simple Realization of Roll Call Random Color

Layout (typesetting)


<body>
	<button onclick="star()"> Begin </button>
	<button onclick="stop()"> End </button>
	<div id="box">
	
	</div>
</body>

css Style


<style>
	#box{
		width: 240px;
		height: 400px;
	}
	#a{
		width: 80px;
		height: 40px;
		line-height: 40px;
		text-align: center;
		float: left;
		background: cyan;
	}
</style>

js code


<script>
 // Declaration 1 Array access user name 
 const arr=[' The Story of Diu Sim ',' Xi Shi ',' Yang Yuhuan ',' Wang Zhaojun ',' Li Bai ',' Zhao Kuangyin ',' Zhu Yuanzhang ',' Little Joe ',' Liu Che '];
 const box=document.getElementById('box');
 // Declaration 1 Global variables 
 let set;
 // console.log(box)
 //  Dynamic creation div, Put the data of the array into the div Medium 
 for (var i = 0; i< arr.length; i++) {
  var div=document.createElement('div');
  div.id='a';
  div.innerHTML=arr[i];
  // console.log(div.innerHTML);
  box.appendChild(div);
 //  Click the Start button to select randomly 1 A name 
 }
 function star(){
 //  Clear before you start 1 Pass timer , Prevent exiting bug Can't stop 
  clearInterval(set);
  // Settings 1 Timer 
  set=setInterval(() => {
   for(var k=0;k<arr.length;k++){
    box.children[k].style.background='';
   }
   var random = parseInt(Math.random() * arr.length);
   box.children[random].style.background = color();
  }, 100)
 }
 //  Click Stop Selecting Name ( Clear timer )
 function stop(){
  clearInterval(set);
 }
 // Encapsulation 1 Random color 
 function color(){
		const r = Math.floor(Math.random() * 255);
		const g = Math.floor(Math.random() * 255);
		const b = Math.floor(Math.random() * 255);
		const rgb='rgb('+r+','+g+','+b+')';
		return rgb;
	}
</script>

Summarize


Related articles: