本文分享使用JavaScript实现长页面蒙版覆盖及禁止页面滚动的具体代码方案。该功能支持在点击特定区域后隐藏蒙版并恢复滚动,同时确保PC端与移动端的良好兼容性,为前端开发提供实用参考。
JavaScript实现页面蒙版与禁止滚动功能
本文通过具体代码示例,介绍如何在JavaScript中实现页面蒙版效果以及禁止页面滚动的功能,供开发者参考学习。
项目核心需求如下:当页面内容较长时,需要添加一个蒙版层;点击特定位置后,蒙版消失且页面恢复可滑动状态;若未点击,则蒙版保持存在并禁止页面滚动。此外,该方案需同时兼容PC端与移动端环境。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name=viewport content="width=device-width,initial-scale=1,user-scalable=no">
<title>蒙版与禁止滚动</title>
<style>
.container{
width:200px;
height:2000px;
background-color:blue;
}
.modal{
width: 100%;
position:fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 999;
background-color: rgba(0,0,0,0.7);
background-size: 100%;
}
.p{
font-size: 50px;
color:red;
text-align:center;
}
</style>
</head>
<body>
<div class="container">
<p>内容</p>
</div>
<!-- 蒙版 -->
<div class="modal">
<p class="p">按钮</p>
</div>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
$(function(){
// 阻止蒙版后页面滑动
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
//移动端
$(".modal").on('touchmove',function(e){
e.stopPropagation();
e.preventDefault();
$('.p').click(function(){
$(this).parent().hide();
})
})
} else {
//PC端
var flag=true;
$('.p').click(function(){
$(this).parent().hide();
$('body').css({ "overflow":'visible'});
flag=false;
})
if(flag)
$('body').css({ "overflow":'hidden' });
}
})
</script>
</html>
以上内容为本文的全部分享,希望对读者的学习与实践有所帮助,同时也欢迎大家继续支持本站获取更多技术资源。