반응형 탭 창 구현하기

Project Diary/HTML + CSS +JS (Haitai WepSite)

화면 크기에 따라 슬라이드 세 개를 나열된 형태에서 탭 창으로 전환하는 반응형 UI를 구현하는 과정 기록


1. HTML 구조 설정

2.  CSS 스타일링

탭 창과 슬라이드의 스타일링을 설정합니다. 반응형 UI를 위해 미디어 쿼리를 사용하여 화면 크기에 따라 다른 스타일을 적용합니다.

/* 공통 스타일링 */
#section .slidePage1 {
  background: #544f4f;
  padding: 200px 0;
}

#section .slidePage1 .productSlideOuter,
#section .slidePage1 .eventSlideOuter,
#section .slidePage1 .mallSlideOuter {
  width: 100%;
}

#section .slidePage1 .tapTitle {
  display: none;
}

/* 슬라이드 스타일링 */
#section .slidePage1 .productSlideOuter .productSlideInner,
#section .slidePage1 .eventSlideOuter .eventSlideInner,
#section .slidePage1 .mallSlideOuter .mallSlideInner {
  width: 300px;
  height: 100%;
  text-align: center;
  background: url(../img/newproduct\ bg.png) no-repeat;
  margin-left: 50%;
  transform: translateX(-50%);
}

/* 슬라이드 내 이미지 스타일링 */
#section .slidePage1 .slideContainer1 .productSlideOuter .productSlide img.contentProduct,
#section .slidePage1 .slideContainer1 .eventSlideOuter .eventSlide img.contentEvent,
#section .slidePage1 .slideContainer1 .mallSlideOuter .mallSlide img.contentMall {
  position: absolute;
  top: 140px;
  left: 0;
}

/* 슬라이드 배경 이미지 숨기기 */
#section .slidePage1 .slideContainer1 .productSlideOuter .productSlide img.bgProduct,
#section .slidePage1 .slideContainer1 .eventSlideOuter .eventSlide img.bgEvent,
#section .slidePage1 .slideContainer1 .mallSlideOuter .mallSlide img.bgMall {
  opacity: 0;
}

/* 탭과 슬라이드 전환 스타일링 */
@media (max-width: 1088px) {
  #section .slidePage1 .tapTitle {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }
  #section .slidePage1 .slideContainer1 {
    display: none;
  }
  #section .slidePage1 .tapContent.on {
    display: block;
  }
}

 

3. JavaScript 코드

화면 크기에 따라 슬라이드와 탭 창을 전환하는 JavaScript 코드를 작성합니다. jQuery를 사용하여 화면 크기에 따라 클래스를 추가하고, 클릭 이벤트를 설정합니다.

// 화면 크기에 따라 클래스 추가
let ww = $(window).width();
if (ww > 1088) {
  $("html").addClass("pc");
} else {
  $("html").addClass("mobile");
}

// 슬라이드 설정
$(".slideContainer1").slick({
  autoplay: true, // 자동 재생
  infinite: true, // 무한 루프
  slidesToShow: 3, // 보여줄 슬라이드 개수
  slidesToScroll: 1, // 스크롤할 슬라이드 개수
  arrows: true, // 화살표 표시
});

// 각 슬라이드에 대한 설정
$(".productSlideInner, .eventSlideInner, .mallSlideInner").slick({
  autoplay: true, // 자동 재생
  dots: true, // 점 네비게이션 표시
  infinite: true, // 무한 루프
  speed: 300, // 슬라이드 속도
  arrows: false, // 화살표 표시 안 함
});

// 탭 클릭 이벤트 설정 (화면 너비가 1088px 이하일 때)
if ($(window).width() <= 1088) {
  $(".tapTitle > li").on("click", function () {
    $(this).addClass("on").siblings().removeClass("on"); // 클릭한 탭 활성화
    let num = $(this).index();
    $(this)
      .parent()
      .next()
      .find(".tapContent")
      .eq(num)
      .addClass("on")
      .siblings()
      .removeClass("on"); // 해당 탭 내용만 표시
  });
}