今更ながらシンプルなポップアップウインドウを作る

本当にいまさらだけど、作ってみた。

  • 大したことはしないので、使うのはjquery.jsのみとする。
  • 画像をクリックしたり、ポップアップウインドウ非表示時にカーソルを合わせるとポップアップウインドウを表示する。
  • 画像からカーソルを離したり、ポップアップウインドウ表示中に画像をクリックするとポップアップウインドウを消す。
  • HTMLはシンプルに。
  • JSはJQueryを使って極力シンプルに。

作った単独で動作可能なサンプル(http://jsdo.it/arfyasu/dQqD を参考にしました):

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Example</title>
    <style type="text/css">
      #boxes .window {
        position: absolute;
        width: 200px;
        height: 300px;
        display: none;
        z-index: 100;
        padding: 20px;
        background-color: #99ccff;
      }
    </style>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script type="text/javascript">
      function showPopup(id) {
        var winH = $(window).height();
        var winW = $(window).width();
           
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2);
        $(id).attr("_display", "true")
        $(id).fadeIn(200);

        return false;
      }
    
      function hidePopup(id) {
        $(id).attr("_display", "false")
        $(id).fadeOut(100);
      }
    
      function switchPopup(id) {
        var display = $(id).attr("_display");
        if (display == "true") {
          return hidePopup(id);
        } else {
          return showPopup(id);
        }
      }
    </script>
</head>
<body>
  <a href="#" onmouseover="showPopup('#popup_contents')" 
    onmouseout="hidePopup('#popup_contents')"
    onclick="return switchPopup('#popup_contents');">
    Click Me
  </a>

  <div id="boxes">
    <div id="popup_contents" class="window">
        ポップアップダイアログ
    </div>
  </div>
</body>
</html>

※ 画像のかわりにただの<a>タグにしてある。