项目中很多使用overflow:scroll的地方,在移动端webview的加持下,出现一些兼容性的问题,于是索性自己搞一个出来,上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>scroll</title>
<style>
.content-box {
width: 450px;
height: 700px;
background-color: pink;
margin: 0 auto;
text-align: center;
overflow: hidden;
}
.c-title {
text-align: center;
}
.item {
display: inline-block;
margin-top: 20px;
text-align: left;
}
.content .c-item {
font-size: 20px;
}
</style>
</head>
<body>
<div class="content-box">
<div class="content">
<div class="item">
<h3 class="c-title">虞美人·春花秋月何时了</h3>
<div class="c-item">春花秋月何时了,往事知多少?</div>
<div class="c-item">小楼昨夜又东风,故国不堪回首月明中!</div>
<div class="c-item">雕栏玉砌应犹在,只是朱颜改。</div>
<div class="c-item">问君能有几多愁?恰似一江春水向东流。</div>
</div>
<div class="item">
<h3 class="c-title">相见欢</h3>
<div class="c-item">无言独上西楼,月如钩。</div>
<div class="c-item">寂寞梧桐深院锁清秋。</div>
<div class="c-item">剪不断,理还乱,是离愁。</div>
<div class="c-item">别是一般滋味在心头。</div>
</div>
<div class="item">
<h3 class="c-title">浪淘沙令·帘外雨潺潺</h3>
<div class="c-item">帘外雨潺潺,春意阑珊。罗衾不耐五更寒。</div>
<div class="c-item">梦里不知身是客,一晌贪欢。</div>
<div class="c-item">独自莫凭栏,无限江山,别时容易见时难。</div>
<div class="c-item">流水落花春去也,天上人间。</div>
</div>
<div class="item">
<h3 class="c-title">虞美人·春花秋月何时了</h3>
<div class="c-item">春花秋月何时了,往事知多少?</div>
<div class="c-item">小楼昨夜又东风,故国不堪回首月明中!</div>
<div class="c-item">雕栏玉砌应犹在,只是朱颜改。</div>
<div class="c-item">问君能有几多愁?恰似一江春水向东流。</div>
</div>
<div class="item">
<h3 class="c-title">相见欢</h3>
<div class="c-item">无言独上西楼,月如钩。</div>
<div class="c-item">寂寞梧桐深院锁清秋。</div>
<div class="c-item">剪不断,理还乱,是离愁。</div>
<div class="c-item">别是一般滋味在心头。</div>
</div>
<div class="item">
<h3 class="c-title">浪淘沙令·帘外雨潺潺</h3>
<div class="c-item">帘外雨潺潺,春意阑珊。罗衾不耐五更寒。</div>
<div class="c-item">梦里不知身是客,一晌贪欢。</div>
<div class="c-item">独自莫凭栏,无限江山,别时容易见时难。</div>
<div class="c-item">流水落花春去也,天上人间。</div>
</div>
</div>
</div>
</body>
<script>
//获取scroll的盒子
let boxEle = document.querySelector('.content-box');
//绑定touchstart事件
boxEle.addEventListener('touchstart', p => {
//设置当前触摸的屏幕Y坐标为自定义属性
boxEle.setAttribute('dragStartY', p.touches[0].screenY);
//计算可滚动出去的内容高度,即内容高度-可视区域高度
let offset = boxEle.scrollHeight - boxEle.clientHeight;
//设置为自定义属性
boxEle.setAttribute('dragOffset', offset);
});
//绑定touchmove事件
boxEle.addEventListener('touchmove', p => {
//获取上一帧的触摸Y坐标
let startY = boxEle.getAttribute('dragStartY');
//设置当前触摸的屏幕Y坐标为自定义属性
boxEle.setAttribute('dragStartY', p.touches[0].screenY);
//注意这里y值触屏位置越往下越大
let offset = p.touches[0].screenY - startY;
//如果为正,则说明用户在下拉,如果为负,则说明用户在上滑,直接用原来的scrollTop减去offset即可
let tgt = boxEle.scrollTop - offset;
//限定一下可滚动位置
if (tgt < 0) tgt = 0;
let dragOffset = boxEle.getAttribute('dragOffset');
if (tgt > dragOffset) tgt = dragOffset;
boxEle.scrollTop = tgt;
});
</script>
</html>
效果如下: