JavaScript 实现简单的 弹出框关闭框

知识点:

  1.javaScript 添加HTML标签

  2.javaScript 添加HTML标签属性

  3.javaScript 追加元素

代码献上:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title> <style type="text/css">
*{
padding: 0;
margin: 0;
}
html,body{
height:100%;
}
#box{
width: 100%;
height: 100%;
}
#content{
position: relative;
top: 150px;
width: 200px;
/*line-height: 200px;*/
height: 200px;
text-align: center;
color: red;
background: green;
margin: auto;
}
#span1{
position: fixed;
background-color: red;
top:0;
right:0;
width: 30px;
height: 30px;
line-height: 30px;
text-align: center;
color: #ffffff;
}
</style>
</head>
<body >
<button id="btn">弹出</button> </body>
<script type="text/javascript">
// 获取dom元素 1.获取事件源
var oBtn = document.getElementById('btn');
// 创建弹出模态框的相关DOM对象
var oDive = document.createElement('div');
var oP = document.createElement("p")
var oSpan = document.createElement('span') // 设置属性
oDive.id = 'box';
oP.id = 'content';
oSpan.innerHTML = 'X';
oP.innerHTML = '恭喜IG获得S8冠军!'; oSpan.id = 'span1;'; // 追加元素
oDive.appendChild(oP);
oP.appendChild(oSpan); // 点击弹出按钮 弹出模态框
oBtn.onclick = function(){
// 动态的添加到body中一个div
this.parentNode.insertBefore(oDive,oBtn)
}
// 点击x, 关闭模态框
oSpan.onclick = function () {
// 移除oDiv元素
oDive.parentNode.removeChild(oDive)
}
</script>
</html>
05-11 13:09