先上实际实现h5页面效果图。
如图实现的需求为:固定header + 固定footer + 可滚动content
如众多网友说的直接给body阻止默认事件,实际上是不行的(代码一)
document.body.addEventListener('touchmove',function(e){
e.preventDefault()
},false)
若想实现页面完全不可滚动的需求,需加一参数才可实现,具体不展开说明,可自行google(代码二)
document.body.addEventListener('touchmove',function(e){
e.preventDefault()
},{ passive:false })
接下来介绍本文的具体解决方案:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1, width=device-width, maximum-scale=1, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.header, .footer {
position: fixed;
width: 100vw;
height: 40px;
line-height: 40px;
text-align: center;
z-index: 3;
}
.header {
top: 0;
border-bottom: 1px solid #e6e6e6;
}
.footer {
bottom: 0;
border-top: 1px solid #e6e6e6;
}
.scrollEle {
position: fixed;
width: 100vw;
top: 40px;
bottom: 40px;
z-index: 2;
background: #fff;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
</style>
</head>
<body>
<div class="header">Header</div>
<div class="scrollEle">
<p>......</p>
<p>......</p>
<p>......</p>
<p>......</p>
</div>
<div class="footer">Footer</div>
</body>
<script>
var startX = 0, startY = 0;
function touchStart(e) {
try {
var touch = e.touches[0],
x = Number(touch.pageX),
y = Number(touch.pageY);
startX = x;
startY = y;
} catch (e) {
alert(e);
}
}
document.addEventListener('touchstart', touchStart);
var ele = document.querySelector('.scrollEle');
ele.ontouchmove = function (e) {
var point = e.touches[0],
eleTop = ele.scrollTop,
eleScrollHeight = ele.scrollHeight,
eleOffsetHeight = ele.offsetHeight,
eleTouchBottom = eleScrollHeight - eleOffsetHeight;
if (eleTop === 0) {
if (point.clientY > startY) {
e.preventDefault();
}
}
else if (eleTop === eleTouchBottom) {
if (point.clientY < startY) {
e.preventDefault()
}
}
};
</script>
</html>
主要思路就是监听content部分滚动,当其滚动到顶部或者底部的时候,阻止其默认事件。