dialogタグで作成したモーダルのサンプル(フェードイン)

これはモーダルです。

モーダルの外側をクリックしても閉じることができます。

<dialog id="modal">
  <p>これはモーダルです。</p>
  <p>モーダルの外側をクリックしても閉じることができます。</p>
  <button id="closeModal">×</button>
</dialog>
::backdrop {
  background: rgba(0, 0, 0, 0.8);
  animation: fadeInBackdrop 0.3s ease;
}

#modal {
  overflow: visible;
  position: relative;
  animation: fadeInModal 0.3s ease;
}

#closeModal {
  position: absolute;
  top: 0;
  right: 0;
  width: 30px;
  height: 30px;
  background: #FFF;
  border: none;
  font-size: 20px;
  font-weight: bold;
  cursor: pointer;
}

@keyframes fadeInModal {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeInBackdrop {
  from {
    background: rgba(0, 0, 0, 0);
  }
  to {
    background: rgba(0, 0, 0, 0.8);
  }
}
const modal = document.getElementById('modal')
const openButton = document.getElementById('openModal')
const closeButton = document.getElementById('closeModal')

// モーダルを開く
openButton.addEventListener('click', () => {
  modal.showModal()
  document.body.style.overflow = 'hidden'
})

// モーダルを閉じる
closeButton.addEventListener('click', () => {
  modal.close()
  document.body.style.overflow = ''
})

// モーダルの外側クリックで閉じる
modal.addEventListener('click', (event) => {
  const rect = modal.getBoundingClientRect()
  if (
    event.clientX < rect.left ||
    event.clientX > rect.right ||
    event.clientY < rect.top ||
    event.clientY > rect.bottom
  ) {
    modal.close()
    document.body.style.overflow = ''
  }
})

元記事を表示する