javascript - 检查用户是否滚动超过一定数量
问题描述
仅当用户滚动超过 > 250 时,我才需要显示按钮backtotop
。我该怎么做?
我的代码:
<template>
<div>
<button v-if="checkScroll" class="goTop" @click="backToTop">
<i class="fa fa-angle-up" aria-hidden="true"></i>
</button>
</div>
</template>
<script>
export default {
methods: {
computed: {
checkScroll() {
if ($(document).scrollTop() > 250) {
return true;
} else {
return false;
}
}
},
backToTop() {
this.$scrollTo('html');
},
}
}
</script>
我的代码不起作用。我没有得到错误。按钮被隐藏。
解决方案
也不要忘记销毁事件:
new Vue({
el: "#app",
data() {
return {
scroll: null
}
},
methods: {
handleScroll(e) {
this.scroll = window.scrollY || window.scrollTop
}
},
created() {
window.addEventListener('scroll', this.handleScroll);
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll);
}
})
html {
height: 3000px; /* some random height for demonstration purpose */
}
button {
position: fixed;
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.2/dist/vue.js"></script>
<!-- scroll to see the button -->
<div id="app">
<button v-show="scroll > 250">foobar</button>
</div>
推荐阅读
- python - 带有 MySQL 更新的多线程
- java - 在非 Spring 管理的 Java 类中使用自动装配的单例 bean
- ruby - Ruby 的 File.exists 变得不区分大小写?
- excel - 有没有办法从 Outlook 的电子邮件正文中提取特定单词以输入 Excel 中的特定单元格?
- spring - sts中的spring boot Maven项目导入错误
- javascript - 从附加到滚动视图的组件更新本机反应中的父组件
- javascript - Firefox 开发工具:是否可以在文档上看到事件监听器?
- javascript - SigmaJS节点定位算法
- apache-spark - 从 cmd 运行 apache spark-kafka-hbase jar 时出错
- c# - How to use EF Core extension methods asynchronously