js를 이용해서 랜덤한 색상을 생성한다.

 

JS

const divs =  document.querySelectorAll('.col');
const randomText = "0123456789ABCDEF";

function createBg() {

   divs.forEach(div => {
      let randomColor = colorGenerator();
      div.style.background = randomColor;
   });

   function colorGenerator() {
      let hash = "#";
      for (i = 0; i < 6; i++) {
         hash += randomText[Math.floor(Math.random() * 16)];
      }
      return hash;
   }
}

setInterval(createBg, 2000);

createBg();

HTML

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Random Color</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
   <link rel="stylesheet" href="style.css" />
</head>
<body>
   <div class="container-fluid">
      <div class="row">
         <div class="col"></div>
         <div class="col"></div>
         <div class="col"></div>
         <div class="col"></div>
         <div class="col"></div>
         <div class="col"></div>
      </div>
   </div> 
   <script src="app.js"></script>
</body>
</html>

 

 

'JavaScript > Vanilla JS' 카테고리의 다른 글

Array.some() (배열내에 요소 찾기)  (0) 2021.03.25
Array.from (객체 복사 및 생성)  (0) 2021.03.23
Array.prototype.forEach()  (0) 2021.03.03
정렬하기 array.sort()  (0) 2021.03.02
클래스 (Class) 3  (0) 2021.02.24