Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

モーダルウィンドウ

Last updated at Posted at 2020-11-03

body {
  font-size: 14px;
}

#open, #close {
  cursor: pointer;
  width: 200px;
  border: 1px solid #ccc;
  border-radius: 4px;
  text-align: center;
  padding: 12px 0;
  margin: 16px auto 0;
}

#mask {
  background: rgba(0, 0, 0, 0.4);
  position: fixed; 絶対位置への配置となるのはabsoluteと同じですが、スクロールしても位置が固定されたままとなります。
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 1;
}

#modal {
  background: #fff;
  width: 300px;
  padding: 20px;
  border-radius: 4px;
  position: absolute; 絶対位置への配置となります。 今回はウィンドウ全体の左上が基準位置
  top: 40px;
  left: 0;
  right: 0;
  margin: 0 auto;
  transition: transform 0.4s; transition に対して、 transform が変化するときには 0.4  かけてね 変化に掛かる時間を指定する
  z-index: 2; 重なりの順序を整数で指定します。0を基準として、値が大きいものほど上になります。
}

#modal > p {
  margin: 0 0 20px;
}

#mask.hidden {
  display: none;
}

#modal.hidden {
  transform: translate(0, -500px); 要素の表示位置を移動させる
}
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>Modal Window</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>
  <section id="modal" class="hidden">
    <p>こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。</p>
    <div id="close">
      閉じる
    </div>
  </section>
  
  <div id="open">
    詳細を見る
  </div>

  <div id="mask" class="hidden"></div>


  <script src="js/main.js"></script>
</body>
</html>

'use strict';

{
  const open = document.getElementById('open');
  const close = document.getElementById('close');
  const modal = document.getElementById('modal');
  const mask = document.getElementById('mask');

  open.addEventListener('click', () => {
    modal.classList.remove('hidden');
    mask.classList.remove('hidden');
  });

  close.addEventListener('click', () => {
    modal.classList.add('hidden');
    mask.classList.add('hidden');
  });

  mask.addEventListener('click', () => {
    close.click(); //closeの'click'イベントを呼んでいる
  });
}

デモ
http://samples.dotinstall.com/s/modal_js_v3/54108/MyModalWindow/index.html

0
1
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?