【问题标题】:How to hide a div when scrolled to bottom?滚动到底部时如何隐藏div?
【发布时间】:2021-01-26 08:15:03
【问题描述】:

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

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

【问题讨论】:

    标签: vue.js nuxtjs


    【解决方案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-show 而不是v-if,具体取决于您的用例。

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

    【讨论】:

      【解决方案2】:
       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 都得到了所有人的支持。即使是 6。这应该是跨浏览器安全的。

      【讨论】:

        猜你喜欢
        • 2018-10-02
        • 2020-03-30
        • 1970-01-01
        • 1970-01-01
        • 2021-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多