对代码做了一些修改,以便更容易的理解,希望对大家有帮助
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>移动模态框</title>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div id="edit_mask" class="none"></div>
<!--遮罩层-->
<div>
<button id="edit">弹出</button>
</div>
<!--弹出编辑框-->
<div class="none edit_popup">
<div class="title">
<a href="javascript:void(0)" class="btn_close">关闭</a>
</div>
</div>
</body>
</html>
css部分
.none {
display: none;
}
.edit_popup {
z-index: 100;
position: fixed;
top: 300px;
left: 100px;
width: 100%;
height: 100%;
background-color: pink;
}
.edit_popup .title {
height: 40px;
position: relative;
}
.edit_popup .btn_close {
position: absolute;
right: 10px;
top: 10px;
}
#edit_mask {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0.8;
background-color: #999999;
z-index: 50;
}
a {
text-decoration: none;
}
js部分
// 关闭
function bindEvents() {
$('#edit').on('click', edit);
$('.btn_close').on('click', close_edit);
}
bindEvents()
function edit() {
var left = ($(document).width() - parseInt($('.edit_popup').css('width'))) / 2;
$('.edit_popup').css('left', left + 'px');
$('.edit_popup').removeClass('none');
$('#edit_mask').removeClass('none');
}
edit()
function close_edit() {
$('.edit_popup').addClass('none');
$('#edit_mask').addClass('none');
}
close_edit()
// 点击空白处 关闭 点击变比按钮也可以关闭
$('#edit_mask').on('click', close_edit);