Vue 自动吸顶

 html 元素:

<div class='container' ref='topTab'>
    <div class="absolute" :class='{fixed:isFixed}'>
        <!-- tab-->
    </div>
    <div>
        <!-- content -->
    </div>
</div>
<style>
    .container{
        padding-top: 40px; position: relative; 
    }
    .absolute{
        position: absolute; width:100%; top:0; left:0;
    }
    .absolute.fixed{
        position: fixed;
    }
</style>

 

绑定事件:

  methods:{
    onScroll () {
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      var offsetTop = this.$refs.topTab.offsetTop
      // console.log(scrollTop , offsetTop)
      if (scrollTop > offsetTop) {
        this.isFixed = true
      } else {
        this.isFixed = false
      }
    },
  },
  created () {
    window.addEventListener('scroll', this.onScroll)
  },
  destroyed () {
    window.removeEventListener('scroll', this.onScroll)
  },

 

posted @ 2018-09-14 18:11  晨の风  阅读(1299)  评论(0编辑  收藏  举报