티스토리 뷰

  • 1~45숫자중에 7개를 무작위로 뽑는다.
  • 뽑은 숫자는 오름차순으로 6개 번호를 보여준다. 7번째는 보너스 번호로 보여준다.

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>로또추첨기</title>
  <style>
    .ball {
      display: inline-block; border: 1px solid black; border-radius: 20px; width: 40px; height: 40px;
      line-height: 40px; font-size: 20px; text-align: center; margin-right: 20px;
    }
  </style>
</head>
<body>
  <div id="result">추첨 결과는?</div>
  <div id="bonus">보너스: </div>
  
  <script>
    const candidate = Array(45).fill().map((v, i) => i+1); // 1~45 숫자를 배열에 채움
    const shuffle = [];
    while (candidate.length > 0) { //1~45 숫자를 무작위 배열
      const random = Math.floor(Math.random() * candidate.length);
      const spliceArray = candidate.splice(random, 1);
      const value = spliceArray[0];
      shuffle.push(value);
    }

    const winBalls = shuffle.slice(0, 6).sort((a, b) => a - b); //무작위 배열에서 공6개를 꺼내어 오름차순으로 변수에 배열로 저장
    const bonus = shuffle[6]; //7번째공을 보너스 변수로 저장
    
    function drawBall(number, $parent) { //공 보여주는 함수
      const $ball = document.createElement('div');
      $ball.className = 'ball';
      $ball.textContent = number;
      $ball.style.backgroundColor = ballColor(number); //공 색깔 입히기
      $parent.appendChild($ball);
    }
	
      function ballColor(number) {
        switch(Math.floor(number/10)) {
            case 0:
              return 'red';
            case 1:
              return 'orange';
            case 2:
              return 'yellow';
            case 3:
              return 'green';
            case 4:
              return 'blue';
            default:
              break;
            }
        }
    
    const $result = document.querySelector('#result');
    for (let i = 0; i < winBalls.length; i++) { //6개 보여줌
      setTimeout(() => {
        drawBall(winBalls[i], $result);
      }, 1000 * (i+1));
    }
    const $bonus = document.querySelector('#bonus');
    setTimeout(() => { //보너스 번호 보여줌
      drawBall(bonus, $bonus);
    }, 7000);
  </script>
</body>
</html>

 

로또추첨기
추첨 결과는?
보너스:

 

출처: https://www.zerocho.com/book/2

 

https://www.zerocho.com/book/2

 

www.zerocho.com

 

댓글
다크모드
Document description javascript psychology
더보기 ,제목1 태그 호버