LoginSignup
2
0

More than 5 years have passed since last update.

グローバルナビやモーダル表示の時に背景を固定する メモ

Posted at

グローバルナビやモーダル表示の時に背景を固定する

グローバルメニューやモーダルを表示したときに、背景を固定することが増えたのでメモ。
スマホでも背景が(多分)固定されます。
今のところは不具合なしのはず。

jQuery

jQuery
var btn = $('.btn');//動作に利用する要素
var flg;//メニューorモーダルが開いてるかの判定用フラグ
var scrollpos;//スクロール値

btn.on('click',function(){
  if(flg !== true){//メニューorモーダルを開くときの動作

    scrollpos = $(window).scrollTop();
    $('body').addClass('fixed').css({ 'top': -scrollpos });

  }else if(flg !== false ){//メニューorモーダルを閉じるときの動作

    $('body').removeClass('fixed').css({ 'top': 0 });
    window.scrollTo(0, scrollpos);

  }
});

CSS

CSS(SCSS)
body.fixed {
  position: fixed;
  width: 100%;
  overflow: hidden;
}
2
0
1

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
2
0