看youtube看到的
新的<dialog></dialog>標籤內建開關api

範例:

const dialog = document.querySelector("dialog")
dialog.show() // 打開dialog(原先位置)
dialog.showModal() // 打開dialog(置中且屏蔽背景)
dialog.close() // 關閉dialog

幾個重點:
1.不用再用CSS display開關
2.用showModal()自動置中且屏蔽背景
3.modal設定css背景方式:

dialog::backdrop {
  background-color: hsl(250, 100%, 50%, 0.25);
}

4.可結合form使用,form提供新的method="dialog",或是form裡面的button設定formmethod="dialog"來關閉

<dialog>
  <form method="dialog">
    <input type="text" />
    <button type="submit">Submit</button><!-- 不會submit-->
    <button formmethod="dialog" type="submit">Cancel</button><!-- 不會submit-->
  </form>
</dialog>

5.如果想要點擊dialog以外的地方自動關閉可用下列程式碼:

dialog.addEventListener("click", e => {
  const dialogDimensions = dialog.getBoundingClientRect()
  if (
    e.clientX < dialogDimensions.left ||
    e.clientX > dialogDimensions.right ||
    e.clientY < dialogDimensions.top ||
    e.clientY > dialogDimensions.bottom
  ) {
    dialog.close()
  }
})

6.dialog.close()方法可以傳值到Dialog.returnValue

Dialog.close(valueToPass)
const getValue=Dialog.returnValue

參考資料:
Modals Will Never Be The Same - HTML dialog Element
影片 The New dialog HTML Element Changes Modals Forever


此人尚未填寫簡介。
按讚的人:

共有 1 則留言


此人尚未填寫簡介。
🏆 本月排行榜
🥇
站長阿川
📝11   💬6   ❤️11
438
🥈
我愛JS
📝1   💬5   ❤️4
89
🥉
AppleLily
📝1   💬4   ❤️1
48
#4
💬1  
5
#5
💬1  
3
評分標準:發文×10 + 留言×3 + 獲讚×5 + 點讚×1 + 瀏覽數÷10
本數據每小時更新一次