JavaScript:ポップアップウィンドウの作成

アニメーションを使ってポップアップウィンドウ(ポップアップボックス)を自作する方法を紹介します。

 

popup1.html

<html>
<head>
<style>
.overlay {
  display:none;
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background-color:rgba(0, 0, 0, 0.2);
  padding-top:200px;
}
.box {
  margin:auto;
  padding:20px;
  width:500px;
  background:-webkit-linear-gradient(top, #0390f0 0%, #61b3ff 100%);
}
.popup {
  -webkit-animation:expansion 0.5s;
}
@-webkit-keyframes expansion {
  from {
    -webkit-transform:scale(0);
  }
  to {
    -webkit-transform:scale(1);
  }
}
</style>
</head>
<body>
<input type="button" value="popup" onclick="document.querySelector('.overlay').style.display='block';">
<div class="overlay">
  <div class="box popup" style="position:relative;">
    <div style="font-family:'MS Gothic'; font-size:27px; position:absolute; top:0; right:0;">
      <strong onclick="document.querySelector('.overlay').style.display='none';">&times;</strong>
    </div>
    <header style="font-family:'MS Gothic'; font-size:25px;">
      タイトル
    </header>
    <div>
      <p>
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
      </p>
    </div>
    <footer>
    </footer>
  </div>
</div>
</body>
</html>
 

 

popup2.html

<html>
<head>
<style>
#box {
  width:0;
  height:0;
  font-size:0;
  background-color:#555eee;
  -webkit-transition-property:width, height, font-size, background-color;
  -webkit-transition-timing-function:linear, linear, linear, linear;
  -webkit-transition-duration:0.5s, 0.5s, 0.5s, 0.5s;
}
#box.expanded {
  width:350px;
  height:200px;
  font-size:20px;
  background-color:#555eee;
  padding:20px;
}
.centering {
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
}
</style>
</head>
<body>
<input type="button" value="open" onclick="$add();">
<input type="button" value="close" onclick="$remove();">
<div id="box" class="centering">
  <p>
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
  </p>
</div>
<script>
function $add() {
  document.querySelector("#box").classList.add("expanded");
}
function $remove() {
  document.querySelector("#box").classList.remove("expanded");
}
</script>
</body>
</html>
 

 


参考サイト