vue实现触底回弹
Vue 实现触底回弹效果
触底回弹是一种常见的交互效果,当用户滚动到页面底部时,页面会轻微回弹,提示用户已到达底部。以下是实现方法:
监听滚动事件
在 Vue 组件的 mounted 钩子中添加滚动事件监听器,判断是否滚动到底部。
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const windowHeight = window.innerHeight;
const scrollHeight = document.documentElement.scrollHeight;
if (scrollTop + windowHeight >= scrollHeight - 50) {
this.triggerBounce();
}
},
triggerBounce() {
// 触底回弹逻辑
}
}
实现回弹动画
使用 CSS 动画或 JavaScript 实现回弹效果。以下是 CSS 动画的实现方式:
triggerBounce() {
const body = document.body;
body.style.transform = 'translateY(-20px)';
body.style.transition = 'transform 0.3s ease';
setTimeout(() => {
body.style.transform = 'translateY(0)';
}, 300);
}
优化性能
为了避免频繁触发回弹,可以添加防抖逻辑:
data() {
return {
debounceTimer: null
};
},
methods: {
handleScroll() {
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(() => {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const windowHeight = window.innerHeight;
const scrollHeight = document.documentElement.scrollHeight;
if (scrollTop + windowHeight >= scrollHeight - 50) {
this.triggerBounce();
}
}, 100);
}
}
移动端适配
在移动端,可能需要使用 touchmove 事件和 transform 来实现更自然的回弹效果:
mounted() {
const el = this.$el;
let startY = 0;
el.addEventListener('touchstart', (e) => {
startY = e.touches[0].clientY;
});
el.addEventListener('touchmove', (e) => {
const y = e.touches[0].clientY;
const scrollTop = el.scrollTop;
const scrollHeight = el.scrollHeight;
const offsetHeight = el.offsetHeight;
if ((scrollTop + offsetHeight >= scrollHeight && y < startY) ||
(scrollTop <= 0 && y > startY)) {
e.preventDefault();
const distance = (y - startY) / 2;
el.style.transform = `translateY(${distance}px)`;
}
});
el.addEventListener('touchend', () => {
el.style.transition = 'transform 0.3s ease';
el.style.transform = 'translateY(0)';
setTimeout(() => {
el.style.transition = '';
}, 300);
});
}
使用第三方库
如果需要更复杂的效果,可以考虑使用第三方库如 better-scroll:
import BScroll from 'better-scroll';
mounted() {
this.scroll = new BScroll(this.$el, {
bounce: true,
bounceTime: 300
});
}
以上方法可以根据具体需求选择或组合使用,实现适合项目的触底回弹效果。







