看youtube看到的 新的

標籤內建開關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 則留言

looks good! 查了一下,各大瀏覽器也都已有支援! https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog