mugyu
6/28/2014 - 5:51 AM

jQueryでモーダルウィンドウ

jQueryでモーダルウィンドウ

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>modal window</title>
  </head>
  <body>
    <style>
      #modal-content {
        z-index: 2;
        display: none;
        position: fixed;
        width: 50%;
        margin: 0;
        padding: 10px 20px;
        border: 2px solid #AAA;
        background: #FFF;
      }

      #modal-overlay {
        z-index: 1;
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 120%;
        background-color: rgba(220, 220, 240, 0.75);
      }

      #modal-open {
        cursor: pointer;
        color: #00f;
        text-decoration: underline;
      }

      #modal-open:hover {
        color: #f00;
      }
    </style>
    <a id="modal-open"><ruby>「世界」!!<rp>(</rp><rt>ザ・ワールド</rt><rp>)</rp></ruby></a>
    <div id="modal-content">
      <div id="modal-close">そして時は動き出す</div>
    </div>

    <!-- jQuery -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script language="javascript">
      $(function() {
        var $MODAL_CONTENT = $("#modal-content");

        $(window).resize(function() {
          $MODAL_CONTENT.css({
            top:  ($(window).height()
                   - $MODAL_CONTENT.outerHeight(true)) / 2,
            left: ($(window).width()
                   - $MODAL_CONTENT.outerWidth(true))  / 2
          })
        }).resize();

        $("#modal-open").click(function() {
          $("body").append('<div id="modal-overlay"></div>');
          $("#modal-overlay").fadeIn("slow");
          $MODAL_CONTENT.fadeIn("slow");
        });

        $(document).on("click", "#modal-close, #modal-overlay", function() {
          $MODAL_CONTENT.fadeOut("slow");
          $("#modal-overlay").fadeOut("slow");
          $("#modal-overlay").remove();
        });
      });
    </script>
  </body>
</html>