๐ก ๊ธํ๊ฒ ํ์ง ๋ง๊ณ ํ๋์ฉ ํ๋ฆ์ ํ์ ํ๊ธฐโโ
์ฌ์ฉํ ๋ด์ฅ ํจ์
โพ Math.floor() = ์์์ ๋ฒ๋ฆฌ๊ธฐ
โพ Math.random() = ๋ฉ์๋๋ 0๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๊ณ 1๋ณด๋ค ์์ ๋ถ๋ ์์์ ์์ฌ ๋์๋ฅผ ๋ฐํ
โพ length = ๊ธธ์ด
โพ linear-gradient = ๊ทธ๋ผ๋ฐ์ด์
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 ๊ฐ์ ธ์ค๊ธฐ