CarouselSlider 구현 중 느낀점

1. 이미지가 로드되는 시점과 동적 HTML 생성 시점이 다르다.

1
2
3
4
5
6
7
8
9
// DOM이 로드되고 동적으로 HTML 생성(렌더링)
window.addEventListener("DOMContentLoaded", render);

// 이미지 로드 후 width 및 opacity 할당
window.addEventListener("load", () => {
$container.style.width = `${document.querySelector("img").clientWidth}px`;
$container.style.opacity = 1;
$container.firstElementChild.style.setProperty("--duration", 400);
});
  • 동적으로 HTML을 렌더링해주는데 DOMContentLoaded가 될 때, 이미지의 width를 가져오고 싶었지만 동적 HTML이 생성되고 약간의 시간 후에 이미지가 로드되어 동적 HTML 생성될 때, 이미지태그의 너비를 가져올 수가 없었다.

  • --duration은 요구 사항에 맞게 초기 렌더링 때 설정해준다.

2. CSS inline style이 아닌 external CSS 값 가져오기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$container.addEventListener("click", (e) => {
// 1. prev || next return
// 2. if (prev) / if (next)
if (!e.target.matches(".carousel-control")) return;
e.target.matches(".prev")
? $container.firstElementChild.style.setProperty(
"--currentSlide",
+getComputedStyle($container.firstElementChild).getPropertyValue(
"--currentSlide"
) - 1
)
: e.target.matches(".next")
? $container.firstElementChild.style.setProperty(
"--currentSlide",
+getComputedStyle($container.firstElementChild).getPropertyValue(
"--currentSlide"
) + 1
)
: "";
});
  • document.querySelector(‘div’).style.getPropertyValue() 메서드는 해당 노드의 인라인 스타일의 속성값을 가져올 수 있다.

  • getComputedStyle(document.querySelector(‘div’)).getPropertyValue() 메서드는 해당 노드의 렌더링을 마친 CSS 속성값을 가져올 수 있다. 즉, 외부 CSS 파일의 속성값을 가져올 수 있다.

3. document.querySelector(‘img’) 요소가 가진 width 종류

  • cssWidth : 컨텐츠의 너비를 말한다.
  • clientWidth : padding을 포함한 너비를 말한다.
  • offsetWidth : border까지 포함한 너비를 말한다.

처음에 이미지 태그의 너비를 자바스크립트로 가져와야하는데, 이미지 태그가 가진 너비 요소가 여러가지라서 각 너비의 특징에 대해 알게 되었다.

앞으로 해당 요소 노드를 console 창에 찍어보면서 어떤 프로퍼티를 포함하고 있는지 확인해보면서 내게 필요한 프로퍼티가 무엇인지 찾아보는 팁을 얻었다.