如何解决Vue2 js滚动调用函数 Live Demo
在查看者滚动一定数量的页面百分比后,无论如何要在 vue 上调用方法吗?
例如,我想运行一种方法来在查看者从上到下滚动 80% 的页面后显示报价。
解决方法
<script>
export default {
mounted() {
window.addEventListener("scroll",this.handleScroll);
},destroyed() {
window.removeEventListener("scroll",methods: {
handleScroll(event) {
// Any code to be executed when the window is scrolled
const offsetTop = window.scrollY || 0;
const percentage = (offsetTop * 100) / document.body.scrollHeight;
// Do something with the percentage
},},};
</script>
注意如果您想做某事(例如 task()
),条件是百分比等于或大于除了某个值,您必须考虑一个数据变量容器,该容器有多少次该条件为真,然后仅执行一次操作。
<script>
export default {
data() {
return {
reached: false,// checker container
};
},methods: {
task() {
console.log("Triggered just one time >= 80");
},handleScroll(event) {
// ... After calculating the percentage ...
if (percentage >= 80) {
if (!this.reached) {
this.task();
this.reached = true;
}
} else this.reached = false;
},};
</script>