HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="submit" value="點(diǎn)我">
<!-- 提交按鈕彈出DOM部分 -->
<div class="mask"></div>
<div class="box">
<!-- 關(guān)閉按鈕 -->
<a class="open">X</a>
<!-- 內(nèi)容 -->
哈哈哈哈哈哈哈
</div>
</body>
</html>
javascript:
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("input").click(function(e){
// 阻止默認(rèn)提交表單事件
e.preventDefault();
// 將彈框位置居中
center($(".box"));
// 遮罩層顯示,此處window也可以換成document,區(qū)別在于遮罩層高度的差別
$('.mask').show().height($(window).height());
// 彈框顯示
$('.box').show();
//彈框彈出后隱藏掉滑動(dòng)條,阻止了滾輪對(duì)頁(yè)面的控制
$("body").css({overflow:"hidden"});
});
}).keydown(function(e){ //document監(jiān)聽按下esc將關(guān)閉彈出框及遮罩層
if(e.keyCode==27){
$('.mask').hide();
$('.box').hide();
// 重新顯示滑動(dòng)條
$("body").css({overflow:"auto"});
}
})
// 關(guān)閉按鈕
$('.open').click(function(e) {
func_close();
})
// 關(guān)閉函數(shù)
function func_close(){
$('.mask').hide();
$('.box').hide();
// 重新顯示滑動(dòng)條
$("body").css({overflow:"auto"});
}
// 居中函數(shù)
function center(obj){
var screenWidth = $(window).width(), screenHeight = $(window).height(); //當(dāng)前瀏覽器窗口的 寬高
var scrolltop = $(window).scrollTop();//獲取當(dāng)前窗口距離頁(yè)面頂部高度
var objLeft = (screenWidth - obj.width())/2;
var objTop = (screenHeight - obj.height())/2 + scrolltop;
obj.css({"left": objLeft + 'px', "top": objTop + 'px','display': 'block'});
}
</script>
CSS:
/*遮罩層樣式*/
.mask{
display:none;
position:absolute;
z-index:10;
left:0;
top:0;
width:100%;
height:100%;
background:#666;
opacity:0.5;
-moz-opacity:0.5;
filter:alpha(opacity=50)
}
/*彈出框樣式*/
.box{
z-index:999;
display:none;
position: relative;
width:340px;
height:180px;
border:solid 1px #999;
border-radius:5px;
background-color:#fff;
box-shadow:0 0 0 1px #00aff0;
text-align:center;
padding-top: 20px;
}
/* 關(guān)閉按鈕 */
.open {
position: absolute;
top: 0;
right: 10px;
}
/*按鈕樣式*/
input{
display:block;
width:100px;
height:30px;
outline:none;
cursor:pointer;
font-size:16px;
}