dialogタグで作成したモーダルのサンプル2(外側クリックで閉じる)
<dialog id="modal">
<div id="modalInner">
<p>これはモーダルです。</p>
<p>モーダルの外側をクリックしても閉じることができます。</p>
<button id="closeModal">×</button>
</div>
</dialog>
::backdrop {
background: rgba(0, 0, 0, 0.8);
}
#modal {
overflow: visible;
position: relative;
}
#closeModal {
position: absolute;
top: 0;
right: 0;
width: 30px;
height: 30px;
background: #FFF;
border: none;
font-size: 20px;
font-weight: bold;
cursor: pointer;
}
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) => {
if (event.target.closest('#modalInner') === null) {
modal.close()
document.body.style.overflow = ''
}
})
元記事を表示する