天天看點

禁止遮罩層下螢幕滾動注意:

<!doctype html>
<html >

	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>Document</title>
		<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
		<style type="text/css">
			.div1 {
				width: 100%;
				height: 3000px;
				background: #2AABD2;
				z-index: 100;
			}

			.div2 {
				width: 50px;
				height: 50px;
				z-index: 200;
				background: orangered;
			}

			.cover {
				height: 100%;
				width: 100%;
				background: #000000;
				opacity: 0.5;
				position: fixed;
				top: 0;
				left: 0;
				z-index: 300;
				display: none;
			}

			.window {
				position: fixed;
				top: 50%;
				left: 50%;
				height: 316px;
				width: 70%;
				margin: -158px 0 0 -35%;
				background-color: white;
				z-index: 20000;
				border-radius: 9px;
				display: none;
			}
		</style>
		<script type="text/javascript">
		</script>
	</head>
	<body>
		<div class="div1">
			<div class="div2"></div>
		</div>
		<div class="cover"></div>
		<div class="window">
			<span class="close">關閉彈窗</span>
		</div>

	</body>
	<script>
		//方法一:當遮罩層出現時,禁止滑鼠滾輪滾動和touchmove事件,比較暴力
		/* $(document).on("click", ".div2", function() {
			$("body").css("overflow", "hidden");
			$(".cover").css("display", "block");
			$(".window").css("display", "block");
		})
		$(document).on("click", ".close", function() {
			$(".cover").css("display", "none");
			$(".window").css("display", "none");
			$("body").css("overflow", "scroll");
		}) */
		//方法二:當遮罩層出現時,禁止觸屏滑動事件,但是沒有禁止滑鼠滾輪滾動
		$(document).on("click", ".div2", function() {
			$(".cover").css("display", "block");
			$(".window").css("display", "block");
			$(".cover").on("touchmove", function(e) {
				e.preventDefault();
			})
		}) 
		$(document).on("click", ".close", function() {
			$(".cover").css("display", "none");
			$(".window").css("display", "none");
		})
        //方法三:當遮罩層出來時,将背景圖層添加一個position:fixed屬性,但是可能會發生位移
        /*$(document).on("click", ".div2", function() {
			$(".cover").css("display", "block");
			$(".window").css("display", "block");
			$(".body").css("position","fixed");
		}) 
		$(document).on("click", ".close", function() {
			$(".cover").css("display", "none");
			$(".window").css("display", "none");
            $(".body").css("position","initial");
		})*/
	</script>
</html>
           

注意:

  • 在方法一中遮罩層導覽列禁用後,導緻底層頁面右側導覽列的隐藏,一旦關閉遮罩層,底層右側導覽列再次出現,這就導緻底層頁面出現位置的變動

  • 在方法二中由于隻是禁止了觸屏滑動事件,而沒有禁止滑鼠滾輪滾動,是以我們在使用chorme調試的時候,不要把滾輪滑動導緻最下層圖層滑動認識是代碼無效!!

  • 在方法三中遮罩層彈出後背景層添加了fixed屬性後,可能對背景層其他元素造成影響,使用的時候需要注意