This article shares with you the jQuery special effect of clicking a button to pop up the mask layer and center the content. Let’s take a look at the final effect:

Since it is a test program, I did not add a close button.
1. Main program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" />
<title>弹出居中遮罩</title>
<meta name= "viewport" content= "width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel= "stylesheet" type= "text/css" href= "css/layout.css" />
</head>
<body>
<section class = "test" >
这里是主体内容<br />
<input type= "button" class = "testButton" value= "弹出遮罩" />
</section>
<section class = "testBg" >
<section class = "testCont" >
这里是弹出的内容测试
</section>
</section>
<script src= "js/jquery-1.11.0.js" type= "text/javascript" charset= "utf-8" ></script>
<script src= "js/layout.js" type= "text/javascript" charset= "utf-8" ></script>
</body>
</html>
|
Copy after login
2. CSS style
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | *{
margin: 0;
padding: 0;
}
.testBg{
position: absolute;
top: 0;
background-color: #000;
filter:alpha(opacity=80);
-moz-opacity:0.8;
opacity: 0.8;
display:none ;
}
.testBg .testCont{
position: absolute;
top: 0;
left: 0;
width:200px;
border: 1px #ffc700 solid;
color: #ffc700;
}
|
Copy after login
3. JS program
This is the focus of this essay. Let’s look at an incorrect JS program:
1 2 3 4 5 6 7 8 9 10 11 12 | $( function (){
$( ".testBg" ).height($(window).height()).width($(window).width());
var testContTop=($(window).height()-$( ".testCont" ).height())/2;
var testContWidth=($(window).width()-$( ".testCont" ).width())/2;
$( ".testCont" ).css({
"top" :testContTop,
"left" :testContWidth
});
$( ".testButton" ).click( function (){
$( ".testBg" ).show();
})
})
|
Copy after login
The above program seems to be fine, so let’s take a look at the output:

The upper and lower spacing is inconsistent during actual measurement.
Then the correct JS program is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $( function (){
$( ".testBg" ).height($(window).height()).width($(window).width());
$( ".testButton" ).click( function (){
$( ".testBg" ).show();
showDiv();
})
})
function showDiv(){
var testContTop=($(window).height()-$( ".testCont" ).height())/2;
var testContWidth=($(window).width()-$( ".testCont" ).width())/2;
$( ".testCont" ).css({
"top" :testContTop,
"left" :testContWidth
});
}
|
Copy after login
As can be seen from the above program, after the mask layer pops up, a function is executed to dynamically set the background size of the popup layer and the top and left spacing of the page, instead of setting the popup when JS is first loaded. layer parameters.
The above is the entire content of this article, teaching you how to achieve the effect of clicking a button to pop up the mask layer and center the content,