滚动到底部时如何隐藏div?

时间:2021-01-26 08:15:03

标签: vue.js nuxtjs

如何在滚动到页面底部时隐藏 div?

    <div id="cookieID">
  <p class="cookie-policy">{{ cookiePolicy }}</p>
</div>

2 个答案:

答案 0 :(得分:1)

试试这个:

<template>
  <div>
    <p v-if="!scrolledToBottom" class="cookie-policy">{{ cookiePolicy }}</p>
  </div>
</template>

<script>
export default {
  data: () => ({
    scrolledToBottom: false,
  }),
  mounted() {
    this.scroll()
  },
  methods: {
    scroll() {
      window.onscroll = () => {
        const bottomOfWindow =
          Math.max(
            window.pageYOffset,
            document.documentElement.scrollTop,
            document.body.scrollTop
          ) +
            window.innerHeight ===
          document.documentElement.offsetHeight

        if (bottomOfWindow) {
          this.scrolledToBottom = true
        }
      }
    },
  },
}
</script>

根据您的用例,您可能更喜欢使用 v-if 而不是 v-show

来源:Check if a user has scrolled to the bottom in Vue.js

答案 1 :(得分:0)

 data() {
   return {
     hasScrolledBottom: false,
   };
 },  

 mounted(){
   window.addEventListener('scroll',   this.onScroll, true);
 },
 beforeDestroy() {
   window.removeEventListener('scroll', this.onScroll, true);
 },

methods: {
  onScroll(){
   var element = e.target;
   if (element.scrollHeight - element.scrollTop === element.clientHeight){
     console.log('bottom scrolled');
     this.hasScrolledBottom = true;
    } else {
     console.log('Im not in bottom scrolled');
     this.hasScrolledBottom = false;
   }

您可以使用变量 hasScrolledBottom 来隐藏 div:

<div id="cookieID" v-if="hasScrolledBottom">
  <p class="cookie-policy">{{ cookiePolicy }}</p>
</div>

仅供参考,scrollHeight 在浏览器中得到广泛支持,更准确地说是 ie 8,而 clientHeightscrollTop 都被所有人支持。即使 ie 6。这应该是跨浏览器安全的。