首页 > 解决方案 > 检查用户是否滚动超过一定数量

问题描述

仅当用户滚动超过 > 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>

我的代码不起作用。我没有得到错误。按钮被隐藏。

标签: javascriptvue.js

解决方案


也不要忘记销毁事件:

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>


推荐阅读