js簡單實作點名器隨機色
布局(排版)
<body>
<button onclick="star()">開始</button>
<button onclick="stop()">結束</button>
<div id="box">
</div>
</body>
css樣式
<style>
#box{
width: 240px;
height: 400px;
}
#a{
width: 80px;
height: 40px;
line-height: 40px;
text-align: center;
float: left;
background: cyan;
}
</style>
js代碼
<script>
//宣告一個陣列存取用戶名
const arr=['貂蟬','西施','楊玉環','王昭君','李白','趙匡胤','朱元璋','小喬','劉徹'];
const box=document.getElementById('box');
//宣告一個全域變數
let set;
// console.log(box)
// 動態創建div,把陣列的資料放到div中
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);
// 點擊開始按鈕隨機選一個名字
}
function star(){
// 開始之前先清除一遍定時器,防止出bug停止不了
clearInterval(set);
//設定一個定時器
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)
}
// 點擊停止選取名字(清除定時器)
function stop(){
clearInterval(set);
}
//封裝一個隨機色
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/82754.html
標籤:其他
下一篇:Vue入門到跑路---vue基礎
