实现思路
记录当前滚动条与文档顶部间的距离,将滚动后滚动条与文档顶部间的距离与滚动前滚动条与文档顶部间的距离做比较,若距离变大,则是向下滚,若距离变小,则是向上滚
完整范例代码
<template>
<div>
<div class="box100">0</div>
<div class="box100">100</div>
<div class="box100">200</div>
<div class="box100">300</div>
<div class="box100">400</div>
<div class="box100">500</div>
<div class="box100">600</div>
<div class="box100">700</div>
<div class="box100">800</div>
<div class="box100">900</div>
<div class="box100">1000</div>
</div>
</template>
<script>
export default {
data() {
return {
// 滚动前,滚动条距文档顶部的距离
oldScrollTop: 0,
}
},
mounted() {
// 监听页面滚动事件
window.addEventListener("scroll", this.scrolling)
},
methods: {
scrolling() {
// 滚动条距文档顶部的距离
let scrollTop = window.pageYOffset || document.documentElement.scrollTop ||
document.body.scrollTop
// 滚动条滚动的距离
let scrollStep = scrollTop - this.oldScrollTop;
// 更新——滚动前,滚动条距文档顶部的距离
this.oldScrollTop = scrollTop;
if (scrollStep < 0) {
alert("滚动条向上滚动了!")
} else {
alert("滚动条向下滚动了!")
}
}
}
}
</script>
<style scoped>
.box100 {
height: 100px;
background: #3a8ee6;
border: 1px solid black;
}
</style>