LoginSignup
1
2

Javascriptで簡易的にモーダルを実装してみる

Last updated at Posted at 2023-11-25

はじめに

現在Javascriptを学習中で、簡易的にモーダルを実装してみました。

実装

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./index.css">
  <title>Document</title>
</head>
<body>
    <!-- モーダルを開くボタン -->
  <button id="modalBtn">モーダルを開く</button>
  <!-- モーダル本体。デフォルトでは非表示にしている -->
  <div id="myModal" class="modal">
    <div class="modal-content">
     <span class="close">✖︎</span>
     <p>モーダルを表示</p>
    </div>
  </div>
<script src="./index.js"></script>
</body>
</html>

CSS

/* モーダルの背景 */
.modal {
    display: none; /* デフォルトでは非表示 */
    position: fixed; /* 画面に固定 */
    z-index: 1; /* 他の要素の上に表示 */
    left: 0;
    top: 0;
    width: 100%; /* 全幅 */
    height: 100%; /* 全高さ */
    overflow: auto; /* スクロール可能 */
    background-color: rgb(0,0,0); /* 背景色 */
    background-color: rgba(0,0,0,0.4); /* 透過 */
}

/* モーダルコンテンツ */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 中央に配置 */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* 幅 */
}

Javascript

// 要素を取得
var modal = document.getElementById("myModal");
var btn = document.getElementById("modalBtn");
var span = document.getElementsByClassName("close")[0];

// ボタンをクリックするとモーダルを開く
btn.onclick = function() {
    modal.style.display = "block";
}

// <span> (x) をクリックするとモーダルを閉じる
span.onclick = function() {
    modal.style.display = "none";
}

// モーダルの外側をクリックすると閉じる
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

実行結果

ボタン押下

モーダル表示

モーダルの×押下 or モーダル外押下でモーダルが消える
という実装ができています。

ezgif.com-video-to-gif.gif

1
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2