jquery弹出层居中

文章描述:

jQuery弹出div并且上下左右居中

<div class="container">
  <div class="open-box"> </div>
  <input type="button" class="btn btn-primary" value="点击弹出"/>
</div>
.open-box{ width:300px; height:300px; background: #f1f1f1;position: fixed; display: none;
top:0; left:0;}
} 
$('.btn').on('click',function(){
   //获取页面的宽度和高度
   var html_w = $(window).width();
   var html_h = $(window).height();
   //获取弹出层的宽度和高度
   var op_box_w = $('.open-box').width();
   var op_box_h = $('.open-box').height();
   //计算距离顶部和左边距离
   var top = (html_h/2)-(op_box_h/2);
   var left = (html_w/2)-(op_box_w/2);
   //给弹出层设置样式属性
   $('.open-box').css({"background-color":"#28a745","top":top+'px',"left":left+'px',"display":"block"});
});

 

发布时间:2022/10/13

发表评论