본문 바로가기

일하는 법

jQuery - Div 가 화면 중간에 위치했을 때 Class 추가하여 화면 조작

반응형
SMALL

PC 웹에서는 특정 배너에 마우스 오버 시 효과를 적용하였는데, 

모바일 웹에서는 마우스 오버 액션이 의미가 없어서, 해당 영역이 화면에 위치했을 때 hover 를 addClass('on') 으로 처리해서 

화면 중간에 위치했을 때 클래스를 추가하는 소스를 gpt를 통해서 구현

 

반응형

 

$(document).ready(function () {
  // 스크롤이나 리사이즈 시 체크
  $(window).on('scroll resize', function () {
    if (window.innerWidth <= 760) {
      $('.card').each(function () {
        const $this = $(this); // card div를 this 로 설정
        const elementTop = $this.offset().top; 해당 div의 Top 위치 값을 가져옴
        const elementHeight = $this.outerHeight(); // 해당 div의 height를 구함
        const windowTop = $(window).scrollTop(); // 화면의 스크롤 위치 가져옴
        const windowHeight = $(window).height(); // 화면 높이를 가져옴
        const windowCenter = windowTop + windowHeight / 2; // 화면 가운데를 체크하기 위해서 현재 화면 높이 50%를 구함

        // 요소의 중간이 화면의 중간 근처에 위치하는지 체크
        if (
          windowCenter >= elementTop &&
          windowCenter <= elementTop + elementHeight
        ) {
          $this.addClass('on');
        } else {
          $this.removeClass('on');
        }
      });
    } else {
      // 해상도가 760px 초과일 경우 클래스 제거
      $('.card').removeClass('on');
    }
  });

  // 초기 체크
  $(window).trigger('scroll');
});

 

모바일 적용을 위한 해상도 체크 :  window.innerWidth <= 760  조건으로 처리

스크롤 및 리사이즈 이벤트 감지 :  scroll  및  resize  이벤트로 위치 변경 확인

화면 중간 계산 :  window.scrollTop() + window.height() / 2 

 

 

See the Pen Untitled by youngjoon (@jun31019) on CodePen.

반응형