js實現(xiàn)簡單的點名器隨機(jī)色實例代碼
更新時間:2020年09月20日 09:33:43 作者:qq_45666837
這篇文章主要給大家介紹了關(guān)于js實現(xiàn)簡單的點名器隨機(jī)色的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
js簡單實現(xiàn)點名器隨機(jī)色
布局(排版)
<body> <button onclick="star()">開始</button> <button onclick="stop()">結(jié)束</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>
//聲明一個數(shù)組存取用戶名
const arr=['貂蟬','西施','楊玉環(huán)','王昭君','李白','趙匡胤','朱元璋','小喬','劉徹'];
const box=document.getElementById('box');
//聲明一個全局變量
let set;
// console.log(box)
// 動態(tài)創(chuàng)建div,把數(shù)組的數(shù)據(jù)放到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);
// 點擊開始按鈕隨機(jī)選一個名字
}
function star(){
// 開始之前先清除一遍定時器,防止出bug停止不了
clearInterval(set);
//設(shè)置一個定時器
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);
}
//封裝一個隨機(jī)色
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>
總結(jié)
到此這篇關(guān)于js實現(xiàn)簡單的點名器隨機(jī)色的文章就介紹到這了,更多相關(guān)js點名器隨機(jī)色內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信公眾號中的JSSDK接入及invalid signature等常見錯誤問題分析(全面解析)
這篇文章主要介紹了微信公眾號中的JSSDK接入及invalid signature等常見錯誤問題分析(全面解析),需要的朋友可以參考下2020-04-04

