<div class="page">
  <div class="absolute-box"></div>
  <button id="modal-open">モーダルをひらく</button>
  <div class="item-list">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
  <p>ああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああああ</p>
</div>
<div class="overlay">
  <div class="modal"></div>
</div>
.page {
  box-sizing: border-box;
  width: 100%;
  height: 1000px;
  background-color: #eee;
}

.absolute-box {
  position: absolute;
  width: 100px;
  height: 100px;
  right: 0;
  background-color: black;
}

.item-list {
  margin-top: 20px;
  width: 100%;
  display: flex;
  border: 1px solid #000;
}

.item {
  width: 25%;
  height: 100px;
  background-color: #e99;
  border: 1px solid #000;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: black;
  opacity: 0.6;
  display: none;
}

.overlay.show {
  display: block;
}
function bodyFixed() {
   //変数の設定
  var $body = $('body');
  var $overlay = $('.overlay');

    $body.css({
      margin: 0,
    });
  
  //スクロール量を保存
  var scrollTop;

  //スクロールを固定
  function bodyFixedOn() {
    scrollTop = $(window).scrollTop();
    const scrollBarWidth = window.innerWidth - document.body.clientWidth;

    $body.css({
      position: 'fixed',
      top: -scrollTop,
      paddingRight: `${scrollBarWidth}px`
    });
  }

  //スクロールの固定を解除
  function bodyFixedOff() {
    $body.css({
      position: '',
      top: '',
      paddingRight: 0
    });

    $(window).scrollTop(scrollTop);
  }

  //モーダルのトリガーをクリックしたとき
  $('#modal-open').on('click', function() {
    bodyFixedOn();
    $overlay.addClass('show');
  });

  //モーダルのオーバーレイをクリックしたとき
  $('.overlay').on('click', function() {
    bodyFixedOff();
    $overlay.removeClass('show');
  });
}

bodyFixed();

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js