1
0

More than 1 year has passed since last update.

モーダルを簡易につくってみる

Last updated at Posted at 2023-01-25

モーダルを簡単に作ってみる
出来上がったやつのサンプルページのリンク、イメージはこんな感じ

image.png

See the Pen Untitled by sueasen (@sueasen) on CodePen.

  • HTML ボタンとモーダル準備
index.html
<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="./style.css">
</head>

<body>

    <button class="openModalBtn modal-proc">モーダル!</button>

    <section class="modalArea">
        <div class="modalBg modal-proc"></div>
        <div class="modalWrapper">
            <div class="modalContents">
                <h1>モーダル</h1>
                <p>ここは適当に変更する</p>
            </div>
            <div class="closeModalBtn modal-proc">×</div>
        </div>
    </section>

</body>

<script src="script.js"></script>

</html>
  • CSS でモーダルの配置・表示/非表示
style.css
@charset "utf-8";

/* モーダル全体 */
.modalArea {
  visibility: hidden;
  opacity : 0;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: .4s;
}

/* モーダル・背景 */
.modalBg {
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity : 0.7;
}

/* モーダル・ダイアログ */
.modalWrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%);
  width: 70%;
  max-width: 500px;
  padding: 10px 30px;
  background-color: #fff;
}

/* モーダル・閉じるボタン */
.closeModalBtn {
  position: absolute;
  top: 0.5rem;
  right: 1rem;
  cursor: pointer;
}

/* モーダル表示 */
.is-show {
  visibility: visible;
  opacity : 1;
}

/* モーダル表示用ボタン */
.openModalBtn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%);
}
  • JavaScript で動きを設定
script.js
/**
 * モーダル操作(表示/非表示ボタン、モーダル・背景)のイベント設定
 */
window.addEventListener('load', (e) => {
    document.querySelectorAll('.modal-proc').forEach(dom => {
        dom.addEventListener('click', () => {
            document.querySelector('.modalArea').classList.toggle('is-show');
        });
    });
});
1
0
0

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
0