はじめに
この実験では、HTML の<dialog>タグを使って Web ページ上にモーダルウィンドウやポップアップを作成する方法を学びます。<dialog>タグを使ってサンプルのダイアログボックスを作成する手順を段階的に案内します。
注:
index.htmlでコーディングを練習し、Visual Studio Code で HTML を書く方法を学ぶことができます。画面右下の「Go Live」をクリックして、ポート 8080 で Web サービスを実行します。その後、Web 8080タブを更新して Web ページをプレビューできます。
index.html に dialog タグを追加する
<dialog> タグには開始タグと終了タグが必要です。このステップでは、基本的な HTML 構造と <dialog> タグを index.html ファイルに追加します。
<!doctype html>
<html>
<head>
<title>Modal Window using HTML dialog tag</title>
</head>
<body>
<h1>Modal Window using HTML dialog tag</h1>
<!-- Adding the dialog tag -->
<dialog>
<p>This is a sample dialog box!</p>
</dialog>
</body>
</html>
ダイアログを開くためのボタンを追加する
このステップでは、ダイアログボックスを開くためのボタンを作成します。ボタンがクリックされたときに JavaScript を使ってダイアログボックスを開閉します。
<!doctype html>
<html>
<head>
<title>Modal Window using HTML dialog tag</title>
</head>
<body>
<h1>Modal Window using HTML dialog tag</h1>
<!-- Adding the dialog tag -->
<dialog id="dialog">
<p>This is a sample dialog box!</p>
</dialog>
<!-- Adding a button to open the dialog -->
<button onclick="document.getElementById('dialog').showModal()">
Open Dialog
</button>
<!-- Adding a button to close the dialog, which is hidden by default -->
<button onclick="document.getElementById('dialog').close()">
Close Dialog
</button>
</body>
</html>
ダイアログに CSS スタイリングを追加する
このステップでは、ダイアログボックスにいくつかの CSS スタイリングを追加して、もっと見栄えが良くなるようにします。
<!doctype html>
<html>
<head>
<title>Modal Window using HTML dialog tag</title>
<!-- Adding styles for the dialog box -->
<style>
dialog {
width: 300px;
height: 150px;
background-color: #f2f2f2;
padding: 20px;
border: 2px solid #000;
border-radius: 10px;
box-shadow: 0px 0px 10px #000;
font-family: Arial, san-serif;
font-size: 18px;
color: #000;
text-align: center;
}
</style>
</head>
<body>
<h1>Modal Window using HTML dialog tag</h1>
<!-- Adding the dialog tag -->
<dialog id="dialog">
<p>This is a sample dialog box!</p>
</dialog>
<!-- Adding a button to open the dialog -->
<button onclick="document.getElementById('dialog').showModal()">
Open Dialog
</button>
<!-- Adding a button to close the dialog, which is hidden by default -->
<button onclick="document.getElementById('dialog').close()">
Close Dialog
</button>
</body>
</html>
これで、HTML ダイアログタグを使ってモーダルウィンドウを作成するための HTML コードは完成です。
まとめ
HTML の<dialog>タグを使ってモーダルウィンドウを作成する実験を正常に完了しました。この実験では、HTML の<dialog>タグを使ってサンプルのダイアログボックスを作成する手順について段階的に説明しました。JavaScript を使ってダイアログボックスを開閉するための簡単なボタンを追加しました。また、ダイアログボックスの外観を改善するためにいくつかの基本的な CSS スタイリングも追加しました。



