3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScriptでポップアップウィンドウを作成

Last updated at Posted at 2020-04-01

完成品

スクリーンショット 2020-04-01 22.34.48.png スクリーンショット 2020-04-01 22.35.07.png

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
</head>
<body>
    <input type="button" id="btn" value="押す"> <!-- 変数に格納 -->
    <div id="box"> <!-- 変数に格納 -->
        <p id="close">× <!-- 変数に格納 -->
            <h2>ポップアップ</h2>
        </p>
    </div>
    
</body>
</html>

###CSS


@charset "UTF-8";

#box {
  background: #FFF;
  border: 1px solid #333;
  box-shadow: 0 10px 10px #999;
  display: none;  /*! id要素に対してdisplay:none  */
  font-family: serif;
  padding: 10px;
  position: relative;
  text-align: center;
  width: 200px;
}

#box > #close {
  background-color: #EEE;
  color: #333;
  cursor: pointer;
  height: 30px;
  line-height: 30px;
  margin: 0;
  position: absolute;
  right: 1px;
  text-align: center;
  top: 1px;
  width: 30px;
}

#box > #close:hover {
  background-color: #F9F9F9;
  color: #999;
}

#btn {
  background-color: rgb(20, 114, 236);
  border: 0;
  color: #FFF;
  cursor: pointer;
  padding: 5px 20px;
}

#btn:hover {
  color: rgb(20, 114, 236);
  border: 1px solid rgb(20, 114, 236);
  background-color: rgb(255, 255, 255);
}

#btn:active {
  background-color: #4A4;
}

JavaScript


window.onload= function(){ //window の load イベントに対応するイベントハンドラ

let box = document.querySelector("#box"); //id要素取得
let btn = document.querySelector("#btn"); //id要素取得
let close = document.querySelector("#close") //id要素取得

let boxstyle = box.style; //boxのstyle値をboxstyleに格納

btn.onclick = function(){ //btnがクリックされた時動かす関数
    if(boxstyle.display === "block"){ 
        boxstyle.display = "none";
    }else{
        boxstyle.display = "block";
    }
};

close.onclick= function(){ //closeがクリックされた時の関数
    boxstyle.display = "none";
};

}
3
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?