javascript/javascript30
[javascript30]Playing with CSS Variables and JS
소영
2021. 7. 7. 13:07
Playing with CSS Variables and JS 설명
padding크기와 blur크기,색을 변경하면 아래 사진의 스타일이 변경된다.
1.input의 type과 dataset 설정
2. css 가상선택자를 사용하여 style설정
3.setProperty 메소드를 이용하여 사진의 스타일 변경
코드
<!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" data-name="wes" data-cool="🐶"><!--data-text 작성 하면 개발자도구에 출력됨-->
<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>
:root{/*최상위 가상선택자*/
--base:#ffc600;
--spacing:10px;
--blur:10px;
}
img{
padding:var(--spacing);
background:var(--base);
filter:blur(var(--blur));
}
.h1{
color:var(--base);
}
/*
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>
const inputs = document.querySelectorAll('.controls input');
const img = document.querySelector('img');
function handleUpdate(){
const suffix = this.dataset.sizing || '';//사이즈가 있으면 나오고, 없으면 공백처리
console.log(this.name);
document.documentElement.style.setProperty(`--${this.name}`,this.value+suffix);
}//style.setProperty(propertyName, value, priority);
inputs.forEach(input => input.addEventListener('change',handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove',handleUpdate));
</script>
</body>
</html>
알게 된 문법
HTML
input[type='range'] : 다이얼 컨트롤
input[type='color'] : 색상 선택기
input의 타입에 따라 유형이 변경되는게 많다.
input[data-sizing='px'] : data-[자유롭게 작성가능한 작성요소]
script에서 dataset요소를 사용할 때(고유코드를 가져올 때) 사용하기 편리하다.
CSS
:root {}
가상 선택자로 html선택자와 같다.
전역 css 변수를 선언하고 싶으면 내부에 --main-color 이렇게 앞에 '--'를 작성하면 된다.
--${작성된 전역변수}는
padding:var(--${작성된 변수})
이렇게 작성해야한다.
JAVASCRIPT
.setProperty()
style.setProperty(propertyName, value, priority);
css속성의 값을 유지하지 않고 업데이트를 할때 사용한다.
change Event
inputs.forEach(input => input.addEventListener('change',handleUpdate));
값이 변화할때 이벤트를 동작시킨다.