본문 바로가기
study_front/javascript

[javascript] 랜덤 로또 번호 뽑기

by developer_j 2024. 4. 2.
728x90
반응형
반응형

랜덤으로 로또번호 뽑기 만들기

- document.querySelector(cs선택자)
- 요소.addEventListener("click", function)

 

결과물

css 진자 못해먹겠다.. 퍼블리셔 존경

 

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>my lotto</title>
</head>
<body>
    <style>
    	/* 동그라미 css */
        div.circle{
            border-radius: 50%;
            width:50px;
            height:50px;
        }
        
        /* 동그라미 안 숫자 css */
        h2{
            width:50px;
            height:50px;
            text-align: center;
        }
    </style>
    
    <button id="lottoBtn">로또번호 뽑기</button>
    <div id="result"></div>
    <script src="app.js"></script>
</body>
</html>

 

 

app.js

function getLottoNumber(){
    // 숫자 6개 + 추가번호 1개
    // 1~45
    let html = "";
    for(let i = 1; i <= 7; i++) {
        const num = Math.round(Math.random() * 44) + 1;

        if(i === 7) {  // 마지막 숫자인 경우 추가번호
            html += ' + ';
        } 

        html += '<div class="circle" style="background-color:' + makeRandomColor() + '">';
        html += '<h2>' + num + '</h2>';
        html += '</div>';
    }
    
    const result = document.querySelector('#result');
    result.innerHTML = html;
}

function makeRandomColor() {
    // https://kimk2062.tistory.com/25 참조
    let r = Math.floor(Math.random() * 127 + 128).toString(16);
    let g = Math.floor(Math.random() * 127 + 128).toString(16);
    let b = Math.floor(Math.random() * 127 + 128).toString(16);
    return '#' + r + g + b ;
}

const lottoBtn = document.querySelector('#lottoBtn');
lottoBtn.addEventListener("click", getLottoNumber)

 

 

728x90
반응형