코드공부방

강제로 body 스크롤막기 (PC, Mobile (iOS, Android..) 모든 환경) 본문

웹퍼블리셔/JavaScript

강제로 body 스크롤막기 (PC, Mobile (iOS, Android..) 모든 환경)

:- ) 2019. 8. 28. 17:59
반응형

레이어팝업을 띄우면 뒤쪽 콘텐츠의 스크롤을 막아달라는 요청이 간혹 있다.
(그냥 스크롤이 가능하게 되길 희망하는 클라이언트도 있다.)

 

레이어팝업

/* CSS */
.hidden {height:100%; min-height:100%; overflow:hidden !important; touch-action:none;}
//Javascript
function scrollDisable(){
    $('html, body').addClass('hidden');
}
function scrollAble(){
    $('html, body').removeClass('hidden');
}

레이어팝업을 띄우는 함수안에 위와 같은 함수를 만들어 넣어주면 된다. 위 함수는 html과 body태그에 "height:100%; overflow:hidden;" 속성을 줘서 현재 보이는 화면 외에는 스크롤이 되지 않게 하는 방식이다.


이게 다냐고? 아니다. (* iOS 버전에 따라 위 코드만으로도 처리 가능하다.)
iOS에서는 보란듯이 위 코드를 넣어도 스크롤이 되어버린다(?) 때문에 아래와 같이 scroll, touchmove, mousewheel 이벤트를 원천적으로 막아버려야 스크롤을 막을 수 있다.

//Javascript
function scrollDisable(){
    $('body').addClass('scrollDisable').on('scroll touchmove mousewheel', function(e){
        e.preventDefault();
    });
}
function scrollAble(){
    $('body').removeClass('scrollDisable').off('scroll touchmove mousewheel');
}

 

반응형
Comments