ํ๋ก ํธ์๋ ๊ฐ๋ฐ์ ํ๋ค๊ฐ ๋์ ์ผ๋ก HTML ์์์ ์คํ์ผ์ ๋ณ๊ฒฝํด์ค์ผ ํ๋ ์ํฉ์ ๋ง๋ฌ๋ค. ๋๋ styled-component
์ ๊ฐ์ CSS-in-JS ๋ฐฉ์์ ์ฌ์ฉํ์ง ์๊ณ ๊ณตํต ์คํ์ผ ๊ฐ๋ค์ CSS์ ๋ณ์๋ก ๊ด๋ฆฌํ๊ณ ์์๊ธฐ ๋๋ฌธ์, ๋ ํ ๋ฒ ์๋ฐ์คํฌ๋ฆฝํธ ์์๋ฅผ ์ ์ธํด ์ค๋ณตํด์ ๊ฐ์ ๊ด๋ฆฌํ๊ณ ๋ถ๋ฌ์ ์ฌ์ฉํด์ผ ํ๋ ๊ฑด์ง ๊ณ ๋ฏผ์ด ์๊ฒผ๋ค.
ํ์ง๋ง ๋คํํ๋ ์๋ฐ์คํฌ๋ฆฝํธ์๋ CSS์ ์ ์ธํ ๋ณ์์ ๊ฐ์ ์ ๊ทผํ๋ API๊ฐ ์กด์ฌํ๋ค!
getComputedStyle() ๊ณผ getPropertyValue()
getComputedStyle()
: ์ธ์๋ก ์ ๋ฌ๋ฐ์ HTML ์์์ ๋ํ ๋ชจ๋ CSS ์์ฑ๊ฐ์ ๋ด์ ์คํ์ผ ๊ฐ์ฒด ๋ฐํgetPropertyValue()
: ์คํ์ผ ๊ฐ์ฒด ์ค ์ธ์๋ก ์ ๋ฌ๋ฐ์ ํน์ ์์ฑ์ ๋ํ ๊ฐ์ ๋ฌธ์์ด๋ก ๋ฐํ
์์
CHANGE ๋ฒํผ์ ํด๋ฆญํ๋ฉด ๋๋ค์ผ๋ก ๋ฐฐ๊ฒฝ์์ด ๋ฐ๋๋ ๋ฐ์ค๋ฅผ ์์๋ก API๋ฅผ ํ ์คํธํด๋ณด์. (๐์ ์ฒด ์ฝ๋๐)
HTML
<div id="app">
<button class="button">CHANGE</button>
<div class="box">HELLO !</div>
</div>
CSS
๋ณ์๋ HTML ๋ฃจํธ์ ์ ์ธํ๋ค.
:root {
--color-primary: #007bff;
--color-secondary: #6c757d;
--color-success: #28a745;
--color-info: #17a2b8;
--color-warning: #ffc107;
--color-danger: #dc3545;
}
JS
์ด์ ์์ ์ค๋ช
ํ ๋ ๋ฉ์๋๋ฅผ ์ฌ์ฉํด :root
์ ์ ์ธํ ๋ณ์์ ๊ฐ์ ๊ฐ์ ธ์ฌ ๊ฒ์ด๋ค.
๋จผ์ ๋๋ค์ผ๋ก ์ปฌ๋ฌ ๋ณ์๋ฅผ ์ ํํ๊ธฐ ์ํ ์ฝ๋๋ฅผ ์์ฑํ๋ค.
const props = [
"--color-primary",
"--color-secondary",
"--color-success",
"--color-info",
"--color-warning",
"--color-danger"
];
const randomProp = props[Math.floor(Math.random() * props.length)];
๊ทธ๋ฆฌ๊ณ html
์์๋ฅผ getComputedStyle()
๋ฉ์๋์ ์ธ์๋ก ์ ๋ฌํด :root
์ ๋ํ ์คํ์ผ ๊ฐ์ฒด๋ฅผ ๋ฐํ๋ฐ๋๋ค(1๏ธโฃ). ๊ทธ ์ค ํน์ ํ๋กํผํฐ(์ฌ๊ธฐ์๋ randomProp
)๋ฅผ getPropertyValue()
์ ์ธ์๋ก ์ ๋ฌํ์ฌ ์ต์ข
์ ์ผ๋ก CSS์ ์ ์ธํ๋ ๊ฐ์ ์ป๋๋ค(2๏ธโฃ).
const root = document.documentElement;
const rootStyle = getComputedStyle(root); // 1๏ธโฃ
const randomColor = rootStyle.getPropertyValue(randomProp); // 2๏ธโฃ
๋ง์ง๋ง์ผ๋ก ๋ฒํผ์ ํด๋ฆญํด์ ์ปฌ๋ฌ๊ฐ ๋ณ๊ฒฝ๋ ์ ์๋๋ก ์ฝ๋๋ฅผ ์์ฑํ๋ค.
function getRandomColorFromCSS() {
const props = [
"--color-primary",
"--color-secondary",
"--color-success",
"--color-info",
"--color-warning",
"--color-danger"
];
const randomProp = props[Math.floor(Math.random() * props.length)];
const root = document.documentElement;
const rootStyle = getComputedStyle(root);
const randomColor = rootStyle.getPropertyValue(randomProp);
return randomColor;
}
function changeBoxColor() {
const box = document.querySelector(".box");
box.style.backgroundColor = getRandomColorFromCSS();
}
const button = document.querySelector(".button");
button.addEventListener("click", changeBoxColor);