๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

random

by ํ›„์•ผ- 2024. 2. 1.

๐Ÿ’ก ๊ธ‰ํ•˜๊ฒŒ ํ•˜์ง€ ๋ง๊ณ  ํ•˜๋‚˜์”ฉ ํ๋ฆ„์„ ํŒŒ์•…ํ•˜๊ธฐโ—โ—

์‚ฌ์šฉํ•œ ๋‚ด์žฅ ํ•จ์ˆ˜

โ—พ Math.floor() = ์†Œ์ˆ˜์  ๋ฒ„๋ฆฌ๊ธฐ

โ—พ Math.random()   =  ๋ฉ”์„œ๋“œ๋Š” 0๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ  1๋ณด๋‹ค ์ž‘์€ ๋ถ€๋™ ์†Œ์ˆ˜์  ์˜์‚ฌ ๋‚œ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜

โ—พ length    = ๊ธธ์ด

โ—พ linear-gradient    = ๊ทธ๋ผ๋ฐ์ด์…˜  

0123

 

1. html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>๊ทธ๋ผ๋ฐ์ด์…˜</title>
    <link rel="stylesheet" href="./css/challege1.css" />
  </head>
  <body>
    <button class="btn">Give me color</button>

    <script src="./js/index.js"></script>
  </body>
</html>

 

 

2. js

const btn = document.querySelector("button");
const colors = [
    "#ef5777",
    "#575fcf",
    "#4bcffa",
    "#34e7e4",
    "#0be881",
    "#f53b57",
    "#3c40c6",
    "#0fbcf9",
    "#00d8d6",
    "#05c46b",
    "#ffc048",
    "#ffdd59",
    "#ff5e57",
    "#d2dae2",
    "#485460",
    "#ffa801",
    "#ffd32a",
    "#ff3f34",
];

function clickrandomcolor() {
    const nowColor1 = colors[Math.floor(Math.random() * colors.length)];
    const nowColor2 = colors[Math.floor(Math.random() * colors.length)];
    document.body.style.background = `linear-gradient(to right, ${nowColor1},${nowColor2})`;
    
}

btn.addEventListener("click", clickrandomcolor) ;

 

3. CSS

body {
    height: 100vh;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;   
}

.btn {
    font-size: 30px;
}

 

โœณ ํ•˜๋‚˜์”ฉ ์‚ดํŽด๋ณด์ž

const btn = document.querySelector("button");

-> ์ฟผ๋ฆฌ์…€๋กœ ์—˜๋ฆฌ๋จผํŠธ button ๋ถˆ๋Ÿฌ์˜ค๊ธฐ

 

const colors = [
    "#ef5777",
    "#575fcf",
    "#4bcffa",
    "#34e7e4",
    "#0be881",
    "#f53b57",
    "#3c40c6",
    "#0fbcf9",
    "#00d8d6",
    "#05c46b",
    "#ffc048",
    "#ffdd59",
    "#ff5e57",
    "#d2dae2",
    "#485460",
    "#ffa801",
    "#ffd32a",
    "#ff3f34",
];

-> colors ๋ผ๋Š” ๋ณ€์ˆ˜ ์•ˆ์— ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ  ์‚ฌ์šฉํ•  ์ปฌ๋Ÿฌ๋“ค์„ ์ง‘์–ด๋„ฃ๊ธฐ

 

function clickrandomcolor() {
    const nowColor1 = colors[Math.floor(Math.random() * colors.length)];
    const nowColor2 = colors[Math.floor(Math.random() * colors.length)];
    document.body.style.background = `linear-gradient(to right, ${nowColor1},${nowColor2})`;
}

-> ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค๊ณ  ๊ทธ ์•ˆ์— ๋žœ๋ค ์ปฌ๋Ÿฌ ๋‘ ๊ฐ€์ง€์˜ ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค๊ธฐ

-> ๋ฏธ๋ฆฌ ๋งŒ๋“ค์–ด ๋‘” ์ปฌ๋Ÿฌ๋“ค์„ ๊ฐ€์ง€๊ณ  ์™€์•ผ ํ•œ๋‹ค.

-> Math.random()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.
(๊ทธ๋Ÿฐ๋ฐ ์ด ๋ฉ”์†Œ๋“œ๋Š” 0~1๊นŒ์ง€์˜ ์ˆซ์ž๋ฅผ 0.132323, 0.545354. 0.656456 ... ์ด๋Ÿฐ์‹์œผ๋กœ ์ถœ๋ ฅ ํ•˜๋Š”๋ฐ..)

-> Math.floor ๋กœ ์†Œ์ˆ˜์ ์„ ๋‚ ๋ ค์ค€๋‹ค.

-> ๋ฐฐ์—ด์˜ ์ˆ˜๋งŒํผ ๋žœ๋ค์„ ๋Œ๋ฆฌ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐฐ์—ด์˜ ๊ธธ์ด๋งŒํผ ๊ณฑํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

btn.addEventListener("click", clickrandomcolor) ;

-> ์ด๋ฒคํŠธ๋ฆฌ์Šค๋„ˆ๋กœ click ๊ฐ€์ ธ์˜ค๊ธฐ