<dialog要素> - ダイアログ
公開日:
dialog要素は、ダイアログを表す要素です。前面に表示されるダイアログを設置できます。表示、非表示を操作するには、JavaScriptが必要です。
概要
- 名前
- dialog
- カテゴリー
- Flow content
- Sectioning content
- 配置できる場所
- Flow contentが期待される場所。
- コンテンツモデル
- Flow content。
- タグの省略
- 開始タグも終了タグも省略できません。
- DOM Interface
- HTMLDialogElement
- 仕様書
- https://html.spec.whatwg.org/multipage/forms.html#the-dialog-element
属性
open
この属性を付けると、ダイアログが開いた状態になる。論理属性。
グローバル属性
全てのタグで利用できるグローバル属性を指定できます。
説明
dialog要素は、ダイアログを表示するための要素です。要素の中身が表示されます。操作はJavaScriptで行ないます。
HTML
<dialog id="syncer">
<h5>ダイアログ</h5>
<p>このダイアログはサンプルです。</p>
<p><button type="button" onclick="this.parentNode.parentNode.close()">閉じる</button></p>
</dialog>
要素に対してshow()
を実行するとダイアログが開き、close()
を実行すると閉じます。
JavaScript
// 要素を取得
var targetElement = document.getElementById( "syncer" ) ;
// 開く
targetElement.show() ;
// 最前面で開く
targetElement.showModal() ;
// 閉じる
targetElement.close() ;
dialog要素は、フォームコントロールと親和性が高いです。form要素のmethod属性をdialog
にすると、ダイアログ用のフォームにすることができます。具体的には送信を実行した時に、サーバーサイドには送信されずにダイアログが閉じ、returnValueプロパティに値が渡されます。送信はcloseイベントでキャッチできます。
HTML
<dialog id="syncer">
<form method="dialog">
<p>ボタンのvalue属性が、returnValueプロパティに渡されます。</p>
<p><button value="ボタン1">ボタン1</button></p>
<p><button value="ボタン2">ボタン2</button></p>
<p><button value="ボタン3">ボタン3</button></p>
</form>
</dialog>
要素に対してshow()
を実行するとダイアログが開き、close()
を実行すると閉じます。
JavaScript
// 要素を取得
var targetElement = document.getElementById( "syncer" ) ;
// イベントを設定
targetElement.onclose = function () {
// button要素のvalue属性が含まれる
alert( this.returnValue ) ;
}
サンプルコード
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>【デモ】<dialog要素> - ダイアログ</title>
<link rel="canonical" href="https://syncer.jp/Web/HTML/Reference/Element/dialog/">
<style>
body {
background-color: #fff ;
}
</style>
</head>
<body>
<p>dialog要素は、ダイアログを設置するための要素です。扱うには、JavaScriptの知識が必要です。</p>
<dialog id="syncer">
<p>ダイアログの内容です。</p>
<p>ボタンをクリックすると閉じます。</p>
<p><button type="button" onclick="this.parentNode.parentNode.close()">閉じる</button></p>
</dialog>
<p><button type="button" onclick="document.getElementById( 'syncer' ).show()">開く</button></p>
</body>
</html>