根据屏幕的宽高,弹框永远在页面垂直水平居中。
页面布局如下:
<!--按钮-->
<div class="checkbox">
<a href="javascript:0;" class="cd-popup-trigger3">播放</a>
</div>
<!--弹框-->
<div class="wrap">
<div class="popup mask">
<p>弹框</p>
<div class="cd-buttons"></div>
<a href="#0" class="cd-popup-close">关闭</a>
</div>
</div>
样式:
.checkbox{
100%;
height:100px;
margin:100px auto;
text-align:center
}
.checkbox a{
display:inline-block;
100px;
height:40px;
border:solid 1px #f00;
color:#f00;
text-align:center;
line-height:40px;
text-decoration:none
}
/*弹框样式*/
.wrap{
position: fixed; //让弹框跟随鼠标滚动
left: 0; //一定要有left和top值
top: 0;
height: 100%;
100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
display: none; //先隐藏
-webkit-transition: opacity 0.3s 0s, visibility 0s 0.3s;
-moz-transition: opacity 0.3s 0s, visibility 0s 0.3s;
transition: opacity 0.3s 0s, visibility 0s 0.3s;
z-index:9999;
}
.wrap.box {
opacity: 1;
display: block; //点击的时候再显示
-webkit-transition: opacity 0.3s 0s, visibility 0s 0s;
-moz-transition: opacity 0.3s 0s, visibility 0s 0s;
transition: opacity 0.3s 0s, visibility 0s 0s;
}
.popup{
position: relative;
400px;
height:250px;
background: #FFF;
border-radius: .4rem .4rem .4rem .4rem;
text-align: center;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
-webkit-transform:scale(0.8);
-moz-transform:scale(0.8);
-ms-transform:scale(0.8);
-o-transform:scale(0.8);
transform:scale(0.8);
-webkit-backface-visibility: hidden;
-webkit-transition-property: -webkit-transform;
-moz-transition-property: -moz-transform;
transition-property: transform;
-webkit-transition-duration: 0.3s;
-moz-transition-duration: 0.3s;
-ms-transition-duration: 0.3s;
-o-transition-duration: 0.3s;
transition-duration: 0.3s;
}
.cd-popup-close{
position: absolute;
right:10px;
top:10px;
z-index: 10;
auto;
height:1.25rem;
display: block;
font-size:14px;
}
.box .popup {
position: absolute;
-webkit-transform:scale(1);
-moz-transform:scale(1);
-ms-transform:scale(1);
-o-transform:scale(1);
transform:scale(1);
}
js代码如下:
jQuery(document).ready(function($){
//打开窗口
$('.cd-popup-trigger3').on('click', function(event){
event.preventDefault(); //阻止默认事件
var mask = $('.mask');
// 动态获取弹框到整个页面的宽度和高度
var sWdith = ($(window).width() - mask.outerWidth())/2; //(整个页面的宽度 - 弹框本身的宽度)/2
var sHeight = ($(window).height() - mask.outerHeight())/2 ;
mask.css('left',sWdith);
mask.css('top',sHeight);
$('.wrap').addClass('box');
});
//关闭窗口
$('.wrap').on('click', function(event){
if( $(event.target).is('.cd-popup-close') || $(event.target).is('.wrap') ) {
event.preventDefault();
$(this).removeClass('box');
}
});
//ESC关闭
$(document).keyup(function(event){
if(event.which=='27'){
$('.wrap').removeClass('box');
}
});
});