移動端彈窗滾動時window窗體也一起滾動的解決辦法


在做移動端項目的時候發現,如果彈窗的內容很多很長,在滑動彈窗時,蒙層下面的window窗體也會跟着一起滾動,這樣帶來很差的視覺體驗:
當時也想了很多辦法,比如判斷滑動的元素,如果是彈窗里面的元素則禁止window的滾動,如果不是,則window可以滾動

雖然在滑動彈窗的時候window體不滾動,但是當滑到彈窗邊緣的時候,window體依然滾動,后來小組長想出了一個辦法

即:在彈出彈窗的時候,設置window最外層定位為fixed,這樣window便不會滾動了,在關閉彈窗的時候,設置window體定位為static,window便可重新滾動。

代碼如下:

HTML代碼:

<div class="demo">
   <div class="btn">點擊彈出彈窗</div>
   <p class="bottom-elem">底部元素</p>      
</div>
<div class="dialog-wrap">
   <div class="dialog">
      <div class="close-btn">點擊關閉彈窗</div>
      <p class="dialog-bottom">底部元素</p>
   </div>
   <div class="layer"></div>
</div>

CSS代碼:

.btn{ width: 180px; height: 40px; background: #ff6677; text-align: center; line-height: 40px;
} .bottom-elem{ margin-top: 1500px;
} .dialog-wrap{ display: none; position: fixed; width: 100%; height: 100%; top: 0; left: 0; z-index: 99;
} .dialog{ position: absolute; top: 50%; left: 50%; width: 450px; height: 500px; background: #fff; transform: translate(-50%,-50%); z-index: 100; overflow: auto; font-size: 26px;
} .dialog-bottom{ margin-top: 500px;
} .layer{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,.65); z-index: 99;
} .close-btn{ width: 150px; height: 50px; background: #e8db14; text-align: center; line-height: 50px; font-size: 20px;
}

JS代碼:

$('.btn').on('tap',function(){
  $('.dialog-wrap').css('display','block');
  $('.demo').css('position','fixed');
});

$('.close-btn').on('tap',function(){
  $('.dialog-wrap').css('display','none');
  $('.demo').css('position','static');
});

效果如圖:

如上所示,無論彈窗滑到頂部還是底部,背景window窗體都不滑動。

雖然解決了問題,但是這樣的寫法有點投機取巧,后續需要想想更周全更高級的方法。

by新手小白的記錄

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM