spacing๊ณผ blur, base color๋ฅผ ์กฐ์ ํ์ฌ ์ด๋ฏธ์ง๋ฅผ ๋ณํ์ํค๊ธฐ.
์ด๊ธฐ์ฝ๋
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scoped CSS Variables and JS</title>
</head>
<body>
<h2>Update CSS Variables with <span class='hl'>JS</span></h2>
<div class="controls">
<label for="spacing">Spacing:</label>
<input id="spacing" type="range" name="spacing" min="10" max="200" value="10" data-sizing="px">
<label for="blur">Blur:</label>
<input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px">
<label for="base">Base Color</label>
<input id="base" type="color" name="base" value="#ffc600">
</div>
<img src="https://source.unsplash.com/7bwQXzbF6KE/800x500">
<style>
/*
misc styles, nothing to do with CSS variables
*/
body {
text-align: center;
background: #193549;
color: white;
font-family: 'helvetica neue', sans-serif;
font-weight: 100;
font-size: 50px;
}
.controls {
margin-bottom: 50px;
}
input {
width: 100px;
}
</style>
<script>
</script>
</body>
</html>
์ด๊ธฐํ๋ฉด
data-sizing์ผ๋ก sizing์ด๋ ๋ณ์์ px์ ์ ์ฅํจ.
์ฐธ๊ณ : https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*
๋ฌธ์ ํธ๋ฆฌ์ ๋ฃจํธ์์๋ฅผ ์ ํํ๋ค.
์ฐธ๊ณ : https://developer.mozilla.org/en-US/docs/Web/CSS/:root
์ด๋์ ๋ ๋ฒ์์ range bar๊ฐ ์๊ธด๋ค.
์ฐธ๊ณ : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range
base์์, ๊ธฐ๋ณธ ์ฌ๋ฐฑ, blur์ ๋.
:root{
--base: #ffc600;
--spacing: 10px;
--blur: 10px;
}
img์ class "h1"์ ๋ณ์์ฌ์ฉ.
img{
padding: var(--spacing);
background: var(--base);
filter: blur(var(--blur));
}
.h1{
color: var(--base);
}
<script>
// .controls์ ๋ชจ๋ input ์ ํ.
const inputs = document.querySelectorAll('.controls input')
function handleUpdate(){
// console.log(this.value);
// console.log(this.dataset);
const suffix = this.dataset.sizing || '';
// console.log(suffix);
//update variable
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}
// use arrow function
inputs.forEach(input => input.addEventListener('change', handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));
</script>
const inputs = document.querySelectorAll('.controls input')
.controls์ ์๋ ๋ชจ๋ inputํ๊ทธ๋ฅผ ์ ํํจ.
inputs.forEach(input => input.addEventListener('change', handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));
๊ฐ์ด ๋ณํ๊ฑฐ๋, ๋ง์ฐ์ค๊ฐ ์์ง์ผ ๋ handleUpdate๋ฉ์๋๊ฐ ๋์.
function handleUpdate(){
const suffix = this.dataset.sizing || '';
//update variable
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}
this.dataset.sizing์ <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px">
์์ data-sizing="px"
๋ก ์ง์ ํด ๋์.
์์ ์ ํ๋ ๊ณณ์์๋ data-sizing์ด ์๊ธฐ ๋๋ฌธ์ ''
๊ฐ ๋ค์ด๊ฐ๊ฒ๋๋ค.
๊ฐ์ ๋ณ๊ฒฝํจ. ๋ณ๊ฒฝ๋๋ ๊ฐ์ '๋ฐ๋ ๊ฐ + suffix'๋ก ๋ณ๊ฒฝ๋จ.