JavaScript 弹窗

弹窗在网页交互中非常常见,常用于给用户进行提示消息,当然目前比较常见的是广告弹窗,此处来演示一下基本的弹窗原理。


弹窗效果示意图:


图1 弹窗效果

弹窗效果有以下几个要点:

(1)弹窗开始时并不显示,当点击按钮之后才显示;

(2)当单击弹窗内部的区域(图1的白色部分),弹窗并不关闭,点击白色部分的”ד符号时会关闭弹窗;

(3)当点击弹窗白色区域之外的灰色部分时(图1),弹窗也会关闭。

(4)弹窗会一直在固定的位置显示,因此要设置弹窗的定位为:position:fixed;


其基本的思路如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS弹窗</title>
<style type="text/css">
*{margin: 0;padding: 0;}
button{ //设置按钮的样式
position: fixed;
width: 60px;
height: 40px;
top: 10px;
left: 200px;
}
.model{
display: none; /*隐藏弹窗*/
position: fixed; /*设置其相对于屏幕窗口进行定位*/
z-index: 100;
left: 0;
top: 0;
width: 600px;
height: 400px;
top: 50px;
left: 200px;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,.4);
}
/*弹窗内容*/
.model-content{
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
height:40%;
}
/*关闭按钮*/
.close{
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover, .close:focus{
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<button id="myBtn">打开弹窗</button>
<!--弹窗-->
<div id="myModel" class="model">
<!-- 弹窗内容 -->
<div class="model-content">
<span class="close">&times;</span>
<p>弹窗内部的文本</p>
</div>
</div>
<script type="text/javascript">
window.οnlοad=function(){
var model=document.getElementById('myModel');
var btn=document.getElementById('myBtn');
var span=document.querySelector(".close");//返回文档中匹配的第一个类名为close的元素


btn.οnclick=function(){ //单击按钮时,窗口会弹出
model.style.display="block";
}


span.οnclick=function(){ //单击"×"符号时,会关闭弹窗
model.style.display="none"
}


window.οnclick=function(event){
if(event.target==model){ //返回触发该事件的节点,如果单击的位置所对应的节点为model时,就隐藏model
model.style.display="none";
}
}
}
</script>
</body>
</html>





  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值