【问题标题】:hide element on scroll within div vuejs3在div vuejs3中滚动隐藏元素
【发布时间】:2025-11-23 02:20:23
【问题描述】:

我试图让一个元素隐藏在一个 div 中的滚动上。我尝试了本教程https://codepen.io/neutraltone/pen/poobdgv,但它在滚动整个窗口时有效。我无法让它在特定的 div 上工作。

  mounted() {
    this.lastScrollPosition = window.pageYOffset
    window.addEventListener('scroll', this.onScroll)
  },
  beforeUnmount() {
    window.removeEventListener('scroll', this.onScroll)
  },

我正在使用 Vuejs 3。我认为问题在于,我无法具体指向 div。我用 this.$ref.name(在 div 上使用 ref="name")而不是 window 进行了尝试,但有些东西没有加起来。

提前致谢!

【问题讨论】:

    标签: html vue.js scroll vuejs3


    【解决方案1】:

    您可以使用 v-on:scroll 侦听器(或简写 (@scroll) 侦听 div 上的滚动事件,然后在处理程序中执行您想要的任何操作(在这种情况下,检查滚动位置,然后隐藏元素):

    <template>
      <div class="scrollable-container" @scroll="scrollHandler">
        <div class="content">
          <div v-show="isVisible" class="to-hide">Scroll Me</div>
        </div>
      </div>
    </template>
    
    <script>
    
    export default {
      data: function() {
    return {
        isVisible: true
      };
    },
      methods: {
        scrollHandler(e) {
          this.isVisible = e.target.scrollTop > 300 ? false : true
        }
      }
    }
    </script>
    
    <style>
    
    .scrollable-container {
      height: 500px;
      width: 300px;
      margin: 200px auto;
      overflow-y: scroll;
      border: 1px solid black;
    }
    
    .content {
      height: 1000px;
    }
    
    .to-hide {
      min-height: 500px;
      background-color: blue;
    }
    
    </style>

    【讨论】: