本文共 2902 字,大约阅读时间需要 9 分钟。
前端开发经常会遇到的一个问题就是制作一个弹框来向用户提示信息,在这个弹框弹出的同时,往往会伴有一个灰色的遮罩层挡住页面内容,同时整个页面被这层遮罩盖住,不可点击也不可滚动。
这里写图片描述
方案一:控制overflow禁止滚动(ios不兼容)
要制作这个效果在PC端非常简单,只需要设置html的高度为100%占满屏幕,并且将html的overflow设置为hidden,即可保证页面不可滚动。
但是同样的问题在移动端情况就有所区别。仅仅设置html的上列属性,在移动端仍然无法禁止页面超出部分的滚动,我们需要设置下面的代码才能在弹框出现的时候禁止页面滚动:1
2 3 4 html.style.overflow="hidden"; html.style.height="100%"; body.style.overflow="hidden"; body.style.height="100%"; 原因是因为移动端是基于touch事件,要禁止基于touch事件的滚动,我们必须在对html禁止滚动的基础之上,再将需要禁止滚动的内容上再增加一个包裹层块级元素,然后将这个包裹层块级元素高度设置为100%并设置overflow:hidden;,那么在这里我们认为body包裹了整个页面,正是我们需要的块级元素,将他也设置为禁止滚动,就可以保证移动端页面的滑动时间不会触发页面滚动。 当用户关闭了弹框,页面也就恢复正常,我们设置如下CSS样式属性来还原整个页面的滚动效果:1
2 3 4 html.style.overflow="visible"; html.style.height="auto"; body.style.overflow="visible"; body.style.height="auto"; 这些样式正是对应CSS属性的默认样式。 然而这个方案有一个缺陷,就是ios系统下不兼容,黑幕的效果没法阻止页面的滚动。下面介绍移动端的另一种解决方案。方案二:绝对/固定布局阻止手势滚动事件冒泡(PC端无效)
正是因为移动端的滚动基于屏幕的touch事件,因此诞生了方案二(手机淘宝就使用了这种方案)。
首先我们需要知道两个前提知识点:1、重叠的两个页面元素,z-index值更高的会优先触发事件监听,从而可以在此控制是否让事件流继续;2、移动端滚动的touch事件,基于事件流。 有了上面两个知识点的基础,我们就可以来理解这种方案的设计思路。方案二的原理是:不对原页面进行任何改动,仅仅只是用一个拥有更高z-index值的,布局为absolute或者fixed布局的黑幕(长宽100%)来挡住整个页面,并且监听黑幕的touchstart事件,在touchstart事件内结束事件流,从而阻挡事件流继续。这样,能够产生滚动效果的touch事件就传不到页面上,也就不会发生滚动。这里写图片描述
下面贴上方案二的完整测试源代码:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> .main-content{ position:relative; width:100%; background-color:#ccc; height:2000px; } .main-content .trigger{ width:200px; height:100px; font-size:30px; color:#000; } .main-content .bottom{ position:absolute; bottom:0; left:0; width:100%; height:200px; background-color:red; } .black-shield{ position:fixed; top:0; left:0; width:100%; height:100%; background-color:rgba(10,10,10,0.4); z-index:10; } .black-shield .info{ font-size:40px; color:#000; border:1px solid; z-index:20; } </style> </head> <body> <div class="main-content"> <button id="trigger" class="trigger">开/关</button> <div class="bottom"></div> </div> <div id="shield" class="black-shield" style="display:none;"> <div id="info" class="info">当前黑幕弹出后,页面应该不可滑动,点击当前文本,关闭黑幕</div> </div> <script> function test2(){ var showShield=false; var shield=document.getElementById("shield"); var trigger=document.getElementById("trigger"); var info=document.getElementById("info"); var body=document.querySelector("body"); var html=document.querySelector("html"); //点击显示黑幕 trigger.addEventListener("click",function(){ shield.style.display="block"; },false); //点击关闭黑幕 info.addEventListener("touchstart",function(){ shield.style.display="none"; },false); //在黑幕层阻挡touch事件 shield.addEventListener("touchstart",function(e){ e.stopPropagation(); e.preventDefault(); },false); } test2(); </script> </body> </html>转载地址:http://bxevb.baihongyu.com/