LoginSignup
1
2

More than 5 years have passed since last update.

JavaScriptでモーダルウィンドウを作ろう(ドットインストールから引用)

Last updated at Posted at 2019-04-25

ドットインストールを参考にしてます。
https://dotinstall.com/
※プレミアム会員のみ閲覧可能

完成イメージ

スクリーンショット 2019-04-25 14.37.53.png
             ↓
スクリーンショット 2019-04-25 14.38.01.png

コード

index.html(jsコードも記載してます)
  <div id="open">
    詳細を見る
  </div>

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

  </div>

  <!-- モーダルウィンドウ部分 -->
  <section id="modal" class="hidden">
    <ul>
      <li>テスト1</li> 
      <li>テスト2</li>
      <li>テスト3</li> 
    </ul>
    <div id="close">
      閉じる
    </div>
  </section>

<script type="text/javascript">
  const open = document.getElementById('open');
  const close = document.getElementById('close');
  const modal = document.getElementById('modal');
  const mask = document.getElementById('mask');

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

  close.addEventListener('click', function(){
    modal.classList.add("hidden");
    mask.classList.add("hidden");

  });

  mask.addEventListener('click', function(){
    // modal.classList.add("hidden");
    // mask.classList.add("hidden");
    // 同じ処理なので、このように書き換えが可能
    close.click();
  });
</script>
body{
  font-size: 30px;
}

#open, #close{
  cursor: pointer;
  width:200px;
  border:1px solid #ccc;
  border-radius: 10px;
  text-align: center;
  padding: 12px 0;
  /*上に30px,左右はauto,下は0*/
  margin:30px auto 0;
}

#mask{
  /*aは、透明度*/
  background: rgba(0,0,0,0.4);
  /*全画面に適用*/
  position: fixed;
  top:0;
  bottom:0;
  right:0;
  left:0;
  z-index: 1;
}

#modal{
  background: #fff;
  width:400px;
  padding:20px;
  border-radius: 5px;
  position: absolute;
  top:40px;
  left:0;
  right:0;
  margin:0 auto;
  transition: 0.4s;
  z-index: 2;
}

#modal > ul{
  list-style: none;
  text-align: center;
  padding:0;
}

#mask.hidden{
  display: none;
}

#modal.hidden{
  /*x軸はそのままで、y軸を−にして、上に持っていく*/
  transform: translate(0, -500px);
}
1
2
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
2