在查看器滚动了一定数量的页面百分比后,是否仍然要在vue上调用一个方法?
例如,在查看器将80%的页面从上到下滚动后,我想运行一种显示报价的方法。
发布于 2021-03-25 10:15:52
<script>
export default {
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
},
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>如果要使用百分比等于或大于某个值的条件来执行某项操作(例如,),则必须考虑一个数据变量容器,即该条件的多少倍为真,并在此之后只执行一次操作。
<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>https://stackoverflow.com/questions/66796918
复制相似问题