공부/javascript

2022.06.30 - javascript 30 [ day3 ] CSS Variables with JS

기묜몬 2022. 6. 30. 11:42

CSS 속성값 변수를 사용하여 style을 변경할 수 있도록 만들었다. 

 

 

[ 결과물 ]

body의 style 속성을 반환하여 이런것을 만들 수 있다니 좀 싱기했다.

input range가 너무 못생겨서 직접 커스텀했다. 

 

[ html ]

1. HTML 데이터 속성은 화면에 안보이게 글이나 추가 정보를 담아놓을 수 있는 방법이다.

data-* 속성은 표준이 아닌 속성이나 추가적인 DOM 속성, Node.setUserData()과 같은 다른 조작을 하지 않고도, 의미론적 표준 HTML 요소에 추가 정보를 저장할 수 있도록 한다. 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="./variables.css" />
    <title>Scoped CSS Variables and JS</title>
  </head>
  <body>
    <h2>Update CSS Variables with <span class="jsText">JS</span></h2>

    <div class="controls">
      <label for="spacing">배경화면 간격 :</label>
      <input
        id="spacing"
        type="range"
        name="spacing"
        min="10"
        max="200"
        value="10"
        data-sizing="px"
      />

      <label for="blur">흐림 처리 :</label>
      <input
        id="blur"
        type="range"
        name="blur"
        min="0"
        max="25"
        value="10"
        data-sizing="px"
      />

      <label for="base">배경색 :</label>
      <input id="base" type="color" name="base" value="#ffc600" />
    </div>

    <img
      src="https://cdn.pixabay.com/photo/2017/08/14/04/20/julia-roberts-2639315_960_720.jpg"
    />

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

 

[ CSS ]

1. CSS 사용자 지정 속성 

중복되는 속성값을 작성하는 상황을 다른 프로그래밍 언어처럼 변수에 값을 저장해서 CSS 속성값으로 사용할 수 있다. 

1) :root{} 가 변수를 전역변수처럼 호출할 수 있도록 선언하는 부분이고, 

2) -- 지정속성명: 값; 의 형태로 선언한다. 

3) 선언된 값은 앨리먼트에서 CSS속성의 속성값으로 호출되어 사용된다. CSS속성명: var(--지정속성명);

:root {
  /* --지정속성명 :  값 */
  --base: #ffc600;
  --spacing: 10px;
  --blur: 10px;
}
img {
  /* css 속성명 : var(--지정속성명) */
  padding: var(--spacing);
  background: var(--base);
  filter: blur(var(--blur));
  max-width: 100%;
  max-height: 100%;
}
.jsText {
  color: var(--base);
}

body {
  text-align: center;
  background: #193549;
  color: white;
  font-family: "helvetica neue", sans-serif;
  font-weight: 100;
  font-size: 50px;
}

.controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 50px;
  font-size: 20px;
}
label {
  margin-left: 15px;
  margin-right: 10px;
}

input {
  width: 100px;
}
input[type="range"] {
  overflow: hidden;
  height: 30px;
  -webkit-appearance: none;
  margin: 10px 0;
  width: 10%;
  background: transparent;
}
input[type="range"]:focus {
  outline: none;
}
input[type="range"]::-webkit-slider-runnable-track {
  width: 100%;
  height: 100%;
  cursor: pointer;
  border-radius: 5px;
  border: 2px solid darkslategrey;
}
input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 30px;
  height: 32px;
  background: #d7ffb0;
  cursor: pointer;
  box-shadow: -90vw 0 0 90vw darkslategrey;
}
input[type="color"] {
  background-color: darkslategrey;
  border: 2px solid darkslategrey;
  height: 30px;
  width: 10%;
}

 

[ JS ]

const inputs = document.querySelectorAll(".controls input");

function handlUpdate() {
  // 마우스가 움직이거나 값이 변경된 앨리먼트의 데이터 속성값이 sizing인 값이 존재한다면 가져오고,
  // 없다면 빈 문자열 "";을 가져온다.
  const suffix = this.dataset.sizing || "";
  // document.documentElement html style 요소를 반환
  document.documentElement.style.setProperty(
    `--${this.name}`,
    this.value + suffix
  );
}

inputs.forEach((input) => input.addEventListener("change", handlUpdate));
inputs.forEach((input) => input.addEventListener("mousemove", handlUpdate));