제목은 3D캐러셀로 붙였지만 사실 캐러셀 관련 내용은 없다 ㅎ
3D로 회전하는 카드의 가운데 요소를 찾으며 작성한 코드라 그렇게 됐다.
예시)
클릭하면 돌아가는 8개의 카드로 이루어져있는데,
(아래의 구조로 이루어져있다.)
const containerList = Array.from(listItem.children);
const carouselLength = listItem.children.length;
let centerCell =
carouselLength % 2 !== 0
? listItem.children[parseInt(carouselLength / 2)]
: listItem.children[0];
centerCell.style.backgroundColor = "red";
containerList에 listItem.chilren으로 담는다.
(ul의 li들을 담는 행위.)
그리고 centerCell을 홀수일 때와 짝수일 때를 생각해서 초기 센터를 잡는다.(현재는 cneterCell을 red로 표시.)
그 뒤
for (let i = 0; i < containerList.length; i++) {
containerList[i].setAttribute("id", i);
}
각 list에 id를 추가해주고,
let centerCount = 0;
function getCenterCell(selectedBtn) {
if (selectedBtn) {
centerCell = listItem.children[++centerCount];
if (centerCount > containerList.length - 1) {
centerCount = -1;
centerCell = listItem.children[++centerCount];
}
} else {
centerCell = listItem.children[--centerCount];
if (centerCount < 0) {
centerCount = containerList.length;
centerCell = listItem.children[--centerCount];
}
}
centerCell.style.backgroundColor = "red";
containerList.forEach((el) => {
if (el.id !== centerCell.id) {
el.style.backgroundColor = "white";
}
});
이 캐러셀은 좌, 우로 움직이기 때문에 selectedBtn으로 구분해주고, 움직이려는 방향에 따라 centerCount 값을 변경해주며 centerCell을 변경해준다.
최초에 0에서 -(마이너스)방향으로 클릭 시와 length이상으로 넘어가는 경우를 대비해 초기화해주는 과정들을 추가해줬다.
그래서 나는 getCenterCell함수를 회전하는 event와 자동회전 함수에 넣어줬다.
실행화면.