HP作ってみる!

(45) モーダルウィンドウを開く

2,166 views

この記事は最終更新から 2832日 が経過しています。

やりたいこと

リンクを押したときに、写真やメモなどをモーダルウィンドウで表示したい。

やってみた

style.css

@charset "utf-8";

div#modalBackground{
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(64,64,64,.5);
  text-align: center;
  z-index: 1;
}

img.img_th{
  width: 120px;
  margin: 30px;
  cursor: pointer;
}

img.img_big{
  width: 300px;
  margin: 30px 0;
  z-index: 2;
}

script.js

$(function(){
  $(".img_th").on('click', function(){
    var src = $(this).attr('src');
    $("#modalBackground").fadeIn();
    $("#modalBackground .img_big").attr('src', src);
  });
  $("#modalBackground").on('click', function(){
    $("#modalBackground").fadeOut();
  });
});

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./style.css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="./script.js"></script>
</head>
<body>

<div id="modalBackground"><img class="img_big" src=""></div>

<img class="img_th" src="./img.jpg">
<img class="img_th" src="./img2.jpg">

</body>
</html>

実行サンプルはこちら。
https://www.dogrow.net/hp/sample/00045/



アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済
  • 2026-05-31: 1回
  • 2026-05-30: 4回
  • 2026-05-29: 1回
  • 2026-05-28: 0回
  • 2026-05-27: 0回
  • 2026-05-26: 0回
  • 2026-05-25: 0回
  • モバイルバージョンを終了