js實現簡單的點名器隨機色例項程式碼
阿新 • • 發佈:2020-09-21
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>
總結
到此這篇關於js實現簡單的點名器隨機色的文章就介紹到這了,更多相關js點名器隨機色內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!