注意点
touchstart 手指下按时触发
touchend 手指放开时触发
touchmove 手指滑动时触发
scrollTop 为滚动条在Y轴上的滚动距离。
clientHeight 为内容可视区域的高度。
scrollHeight 为内容可视区域的高度加上溢出(滚动)的距离。
<div
class="home"
ref="home"
id="home"
@touchstart="touchstart"
@touchend="touchend"
@touchmove="touchmove"
>
<div
class="top-text"
:class="{ 'end-load': showTopTextEnd }"
v-show="showTopText"
:style="{ height: topHeight + 'px' }"
>
下拉刷新
</div>
<ul class="ul">
<li class="li" v-for="(item, index) in li" :key="index">
{{ item }}
</li>
</ul>
<div
class="bottom-text"
v-show="showBottomText"
:style="{ height: bottomHeight + 'px' }"
>
上拉刷新
</div>
</div>
样式比较简单,不要在意细节
.home
height 3rem
overflow auto
.ul
.li
padding 20px
.bottom-text,.top-text
background-color red
.end-load
transition-duration .5s
data(){
startY: 0,
endY: 0,
topHeight: 0,
bottomHeight: 0,
showTopText: false,
showTopTextEnd: false,
showBottomText: false
}
// 方法
touchstart(e) {
this.startY = e.changedTouches[0].pageY;
// console.log("touchstart", this.startY);
},
touchend(e) {
// console.log("touchend", e.changedTouches[0].pageY);
this.endY = e.changedTouches[0].pageY;
if (this.endY - this.startY > 1) {
this.topHeight = 50;
this.showTopTextEnd = true;
setTimeout(() => {
this.showTopText = false;
this.showTopTextEnd = false;
}, 2000);
}
if (this.startY - this.endY > 0) {
this.bottomHeight = 50;
setTimeout(() => {
this.showBottomText = false;
}, 1000);
}
},
touchmove(e) {
// console.log("touchmove", e.changedTouches[0].pageY);
e;
const marginTop = document.getElementById("home").scrollTop;
const moveTop = e.changedTouches[0].pageY;
// console.log(marginBottom);
// 距离顶部 下拉刷新
// console.log(marginTop);
this.topHeight = moveTop - this.startY;
if (this.topHeight > 0 && marginTop === 0) {
this.showTopText = true;
}
const marginBottom =
document.getElementById("home").scrollTop +
document.getElementById("home").clientHeight -
document.getElementById("home").scrollHeight;
this.bottomHeight = this.startY - moveTop;
// 距离底部 上拉加载
if (this.bottomHeight > 0 && marginBottom === 0) {
console.log(marginBottom);
this.showBottomText = true;
}
}