关于页面中弹窗的定位问题

在做运营活动页面的时候,有时候一些活动会有很多弹窗,而弹窗要定位在页面中央的位置,即对div进行水平垂直居中,这个并不难做

运营活动通常要用zepto进行开发,轻便简洁,方便操作页面中的DOM,但是当用zepto中的show和hide来切换弹窗的时候便会出现问题

这个问题我已经遇到过好几次了,之前想不通,后来才发现问题所在:

HTML代码如下:

 1 <div class="button" id="button1">点击出现弹框1</div>
 2 <div class="button" id="button2">点击出现弹框2</div>
 3 
 4 <div class="dialog-wrap"> 
 5    <!-- 第一个弹窗 -->
 6     <div class="dialog" id="dialog1">
 7         <div>this is the first dialog</div>
 8     </div>
 9    <!-- 第二个弹窗 -->
10     <div class="dialog" id="dialog2">
11         <div>this is ths second dialog</div>
12     </div> 
13     <!-- 半透明蒙层 -->
14     <div class="layer"></div>
15 </div>

css代码如下:

 1 .dialog-wrap{
 2    width: 100%;
 3    height: 100%;
 4    display: none;
 5    position: absolute;
 6    top: 0;
 7    left: 0;
 8 }
 9 .layer{
10    width: 100%;
11    height: 100%;
12    position: absolute;
13    top: 0;
14    left: 0;
15    background: rgba(0,0,0,.85);
16    z-index: 999;
17 }
18 .dialog{  
19    position: absolute;
20    top: 50%;
21    left: 50%;
22    transform: translate(-50%,-50%);
23    -webkit-transform:translate(-50%,-50%);
24    z-index: 1000;    
25 }
26 #dialog1{
27    width: 500px;
28    height: 200px;
29    border: 1px solid black;
30    background: #fff;
31    border-radius: 10px;
32    text-align: center;
33    line-height: 200px;
34    font-size: 30px;
35    display: none;
36 }
37 #dialog2{
38    width: 500px;
39    height: 300px;
40    background: #fff;
41    border-radius: 10px;
42    line-height: 300px;
43    text-align: center;
44    font-size: 30px;
45    display: none;
46 }

js代码如下所示:

 1 $('#button1').on('click',function(){
 2     $('.dialog-wrap').show();
 3     $('#dialog1').css('display','block');
 4 })
 5 $('#button2').on('click',function(){
 6     $('.dialog-wrap').show();
 7     $('#dialog2').show();
 8 })
 9 $('.layer').on('tap',function(){
10     $('.dialog-wrap').hide();
11     $('#dialog1').hide();
12     $('#dialog2').hide();
13 })

对弹窗1和弹窗2的不同操作,第一个弹窗是 $('#dialog1').css('display','block');  第二个弹窗是  $('#dialog2').show();

然后来看对应的效果:

        

第一个弹窗在页面中央位置,而第二个弹窗却偏了很多

以前我在写弹窗的切换时为了方便都是用的show和hide来实现,但是明明定位在中央的弹窗在用了show之后却偏了,

当时不明白为什么,只能在对应的弹窗中再加上下面的代码:margin-left:-250px;margin-top:-100px;  

这样是有作用的,弹窗显示在页面中央,但是如果页面中有很多个弹窗,而且每个弹窗的大小样式都不一样时,这样就需要为每个弹窗单独定位,比较麻烦

后来在调试控制台的时候,发现用了show的弹窗被自动加上了一些样式,如下所示:

这才发现,原来元素在用了show之后,会被默认加上如上代码,而transform:scale(1,1)使元素显示的同时刚好覆盖住了我对弹窗设计的样式:transform: translate(-50%,-50%);

所以弹窗才会偏,而用了  $('#dialog1').css('display','block');  就不会被覆盖。

做了好几个活动之后终于发现问题所在啦,以后再也不用为每个弹窗单独定位了,鼓掌!!

原文地址:https://www.cnblogs.com/lynnmn/p/6144322.html