Menu
Coddy logo textTech

モーダル (開閉)

CoddyのHTMLジャーニー「JavaScript in Action」セクションの一部 — レッスン 3/27。

モーダルは、ユーザーの注意を引くためにページの上部に表示される小さなウィンドウです。ログインフォーム、通知、または確認によく使われます。見た目は次のようになります: 

主要な概念:

  1. モーダルはデフォルトで非表示です (display: none)。
  2. 「Open」ボタンをクリックすると、openModal() 関数が実行され、display: block が設定されます。
  1. モーダル内では、閉じるボタン (×)closeModal() 関数を実行し、display: none を設定します。
  2. 多くの場合、モーダルの外側(暗いオーバーレイ部分)をクリックすることでも閉じることができます。
<!-- モーダルを開くボタン -->
<button onclick="openModal()">モーダルを開く</button>

<!-- モーダルのオーバーレイとコンテンツ -->
<div id="overlay" style="display:none;">
  <div class="modal">
    <span onclick="closeModal()">×</span>
    <p>これはモーダルウィンドウです。</p>
  </div>
</div>

<script>
  function openModal() {
    document.getElementById("overlay").style.display = "block";
  }
  function closeModal() {
    document.getElementById("overlay").style.display = "none";
  }
</script>
challenge icon

チャレンジ

簡単

宇宙をテーマにしたボタンがあり、クリックするとモーダルウィンドウに興味深い宇宙の事実が表示されるウェブページがあります。いずれかの宇宙の事実ボタンがクリックされると、openModalという関数が実行されます。あなたのタスクは、モーダルウィンドウが表示されるようにopenModalの中にコードを記述することです。

  • これを行うには、IDが"fact"である要素のdisplayプロパティを"block"に設定してください。

自分で試してみよう

<!DOCTYPE html>
<html>
<head>
  <title>Space Facts – Modal Example</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <h1>Space Facts</h1>
  <p>Click the button below to learn something cool about space.</p>

  <!-- Buttons that open modals -->
  <button onclick="openModal('fact')">Fact 1</button>

  <!-- Overlay + Modal Content -->
  <div id="overlay" class="overlay" onclick="closeModal()">
    <div id="fact" class="modal">
      <span class="close-btn" onclick="closeModal()">×</span>
      <h2>Shooting Stars</h2>
      <p>Shooting stars are actually tiny meteors burning up as they enter Earth’s atmosphere.</p>
    </div>
  </div>

  <script src="script.js"></script>
</body>
</html>
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

JavaScript in Actionのすべてのレッスン