<main class='main'>
  <div class='item'>
    <div class='box'></div>
    <button type='button' class='trigger js-modal-toggle'>モーダルウィンドウを開く</button>
  </div>
</main>
<dialog class='modal js-modal' aria-labelledby='modal-title01' autofocus>
  <div class='modal-container'>
    <h2 id='modal-title01' class='modal-title'>モーダルウィンドウタイトル</h2>
    <p>
      <a href='#' class='modal-link'>モーダルウィンドウ内フォーカス可能要素</a>
    </p>
    <button type='button' aria-label='モーダルウィンドウを閉じる' class='modal-trigger js-modal-toggle'></button>
  </div>
</dialog>
.main {
  height: 100dvh;
  display: grid;
  place-items: center;
  padding: 30px;

  .item {
    min-width: 300px;
  }

  .box {
    aspect-ratio: 1;
    background-color: #ccc;
  }

  .trigger {
    width: 100%;
    display: block;
    margin-inline: auto;
    margin-top: 20px;
    color: #333;
    background-color: #fff;
    padding: 16px;
    border-radius: 30px;
    font-weight: 700;
  }

  .link {
    color: #fff;
    text-decoration: underline;
    text-align: center;
    padding-top: 30px;
  }
}

.modal {
  width: 100%;
  height: 100%;
  background-color: transparent;
  opacity: 0;
  overflow: clip auto;
  transition: opacity 0.3s ease;

  &.is-open {
    opacity: 1;

    &::backdrop {
      opacity: 1;
    }
  }

  &::backdrop {
    background-color: rgba(124, 255, 255, 0.3);
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  .modal-container {
    display: grid;
    place-content: center;
    place-items: center;
    row-gap: 30px;
    width: 640px;
    aspect-ratio: 1;
    position: absolute;
    inset: 0;
    margin: auto;
    z-index: 1;
    background-color: #fff;

    .modal-title {
      font-weight: 700;
      font-size: 36px;
    }

    .modal-link {
      color: #333;
      text-decoration: underline;
    }

    .modal-trigger {
      display: grid;
      grid-template-areas: "line";
      place-items: center;
      width: 60px;
      aspect-ratio: 1;
      border: 2px solid #333;
      position: absolute;
      top: 10px;
      right: 10px;

      &::before,
      &::after {
        grid-area: line;
        content: "";
        width: 40px;
        height: 2px;
        background-color: #333;
      }

      &::before {
        rotate: 45deg;
      }

      &::after {
        rotate: -45deg;
      }
    }
  }
}

* {
  &:focus {
    outline: 2px solid blue;
  }
}

body {
  width: 100%;
  background-color: #333;
}

button {
  background-color: transparent;
  outline: none;
  border: none;
  appearance: none;
  cursor: pointer;
}

dialog {
  width: unset;
  max-width: unset;
  height: unset;
  max-height: unset;
  padding: unset;
  margin: unset;
  color: unset;
  background-color: unset;
  border: unset;
  overflow: unset;
}
View Compiled
class Modal {
  constructor({
    dialog = "",
    toggleTrigger = ""
  }) {
    // DOM要素
    this.dialog = document.querySelector(dialog);
    if (!this.dialog) return;
    this.toggleTriggers = document.querySelectorAll(toggleTrigger);
    this.body = document.body;
    this.focusableEls = this.dialog.querySelectorAll(
      'a[href], area[href], input:not([disabled]):not([type="hidden"]):not([aria-hidden]), select:not([disabled]):not([aria-hidden]), textarea:not([disabled]):not([aria-hidden]), button:not([disabled]):not([aria-hidden]), iframe, object, embed, [contenteditable], [tabindex]:not([tabindex^="-"])'
    );
    // フラグ
    this.isOpen = this.dialog.open;
    this.isAnimating = false;
  }

  // 初期化
  init() {
    this.toggleTriggers.forEach((trigger) => {
      trigger.addEventListener("click", this._toggle.bind(this));
    });
    this.dialog.addEventListener("click", (e) => {
      if (e.target === this.dialog) {
        this._toggle();
      }
    });

    this.dialog.addEventListener("keydown", this._handleKeyAction.bind(this));
  }

  // 破棄
  destroy() {
    this.toggleTriggers.forEach((trigger) => {
      trigger.removeEventListener("click", this._toggle.bind(this));
    });
    this.dialog.removeEventListener("click", (e) => {
      if (e.target === this.dialog) {
        this._toggle();
      }
    });
    this.dialog.removeEventListener(
      "keydown",
      this._handleKeyAction.bind(this)
    );
  }

  // 背面スクロール抑制
  _scrollFixed(boolean) {
    let scrollY;
    if (boolean) {
      scrollY = window.scrollY;
      this.body.style.position = "fixed";
      this.body.style.top = `-${scrollY}px`;
    } else {
      scrollY = this.body.style.top;
      this.body.style.removeProperty("position");
      this.body.style.removeProperty("top");
      window.scrollTo(0, parseInt(scrollY || "0") * -1);
    }
  }

  // アニメーションの待機
  async _waitAnimation(target) {
    const animations = target.getAnimations();
    if (animations.length === 0) {
      return Promise.resolve();
    } else {
      await Promise.allSettled(
        animations.map((animation) => animation.finished)
      );
    }
  }

  // キーボード操作
  _handleKeyAction(e) {
    const firstFocusableEl = this.focusableEls[0];
    const lastFocusableEl = this.focusableEls[this.focusableEls.length - 1];
    switch (e.key) {
      // Tab(フォーカストラップ)
      case "Tab":
        // Shift + Tab(戻る)
        if (e.shiftKey) {
          if (document.activeElement === firstFocusableEl) {
            e.preventDefault();
            lastFocusableEl.focus();
          }
        } else {
          // Tab(進む)
          if (document.activeElement === lastFocusableEl) {
            e.preventDefault();
            firstFocusableEl.focus();
          }
        }
        break;
      // Esc(閉じる)
      case "Escape":
        e.preventDefault();
        this._toggle();
        break;
    }
  }

  // モーダルの開閉
  async _toggle() {
    if (this.isAnimating) return;
    this.isAnimating = true;
    this.isOpen = !this.isOpen;
    this._scrollFixed(this.isOpen);

    if (this.isOpen) {
      this.dialog.showModal();
      requestAnimationFrame(() => {
        requestAnimationFrame(async () => {
          this.dialog.classList.add("is-open");
          await this._waitAnimation(this.dialog);
          this.isAnimating = false;
        });
      });
    } else {
      this.dialog.classList.remove("is-open");
      await this._waitAnimation(this.dialog);
      this.dialog.close();
      this.isAnimating = false;
    }
  }
}

// クラスの実行
const modal = new Modal({
  dialog: ".js-modal",
  toggleTrigger: ".js-modal-toggle"
});
modal.init();
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.