LoginSignup
283
280

More than 5 years have passed since last update.

モーダルを表示したときに背景部分はスクロールできないようにする

Last updated at Posted at 2014-11-20

モーダルを表示させたとき、何も考えずにコーディングするとモーダルをスクロールしたいのに背景までスクロールされちゃう、
なんてことに陥りがち。
(モーダルの上端・下端を超えるスクロールをしたときや、モーダル外にカーソルを置いてスクロールしたとき等)
これを防ぐには、モーダルが表示されているときは背景要素をfixedにするのが良さげ。

index.html
<div id="wrapper">
    <p class="open">
        <button>open modal</button>
    </p>
</div>
<section id="modal">
    <!--modal content -->
</section>
main.js

// include jQuery

var current_scrollY;

// OPEN MODAL
$( '.open button' ).on( 'click', function(){
  current_scrollY = $( window ).scrollTop(); 

  $( '#wrapper' ).css( {
    position: 'fixed',
    width: '100%',
    top: -1 * current_scrollY
  } );

  $( '#modal' ).show();

} );

// CLOSE
$( '#modal' ).on( 'click', function( e ){
  if ( e.target.tagName.toLowerCase() === 'section' ){
    $( '#wrapper' ).attr( { style: '' } );
    $( 'html, body' ).prop( { scrollTop: current_scrollY } );

    $( this ).hide();
  }
} );

wrapperをposition: fixed; に変えたとき、
何もしないと上端が0に戻ってしまうので、
現状のスクロール位置をスタイルのtopプロパティにあてることで
背景の位置を維持させます。

また、モーダルを閉じる際には、style指定をリセットすることでfixedを解除させます。
更に、スクロール位置が0に戻ってしまっているので、開くタイミングで保持しておいた値まで移動させましょう。

気をつけるべき点としては、背景要素とモーダル要素を兄弟関係に配置することです。
親子にしてしまうと、モーダルまでfixedされてしまうので。

283
280
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
283
280