const messageBox = ref()
let oldScrollTop: number = 0; // 记录上一次滚动结束后的滚动距离
const scrollTop = ref<number>(0); // 记录当前的滚动距离
const scrollFixedStatus = ref<boolean>(true);
function handleScroll() {
messageBox.value.addEventListener('scroll', () => {
//获取dom滚动距离
scrollTop.value = messageBox.value.scrollTop;
//获取可视区高度
const offsetHeight = messageBox.value.offsetHeight;
//获取滚动条总高度
const scrollHeight = messageBox.value.scrollHeight;
console.log('scrollTop.value', scrollTop.value, scrollHeight, offsetHeight)
if (scrollTop.value + offsetHeight >= scrollHeight) {
// 把距离顶部的距离加上可视区域的高度 等于或者大于滚动条的总高度就是到达底部
console.log("已滚动到底部");
// 获取消息数据
if (messagePageData.value.total % 10 !== 0) {
postData.value.pageNumber++
getMessageList()
}
}
});
}
onMounted(() => {
handleScroll();
});
onBeforeUnmount(() => {
messageBox.value.removeEventListener('scroll', () => { }); // 离开当前组件别忘记移除事件监听
});
watch(
() => scrollTop.value,
(newValue, oldValue) => {
setTimeout(() => {
if (newValue === window.scrollY) {
// 延时执行后当newValue等于window.scrollY,代表滚动结束
console.log('滚动结束');
oldScrollTop = newValue; // 每次滚动结束后都要给oldScrollTop赋值
// scrollFixedStatus.value = true;
}
}, 20); // 必须使用延时器,否则每次newValue和window.scrollY都相等,无法判断,20ms刚好大于watch的侦听周期,故延时20ms
if (oldScrollTop === oldValue) {
scrollFixedStatus.value = false;
// 每次滚动开始时oldScrollTop与oldValue相等
// console.log('滚动开始');
}
}
);
记录vue3针对某个div滚动到底部的实践
最新推荐文章于 2024-09-27 16:44:19 发布