主要是通过浏览器事件监听函数,判断距离顶部的高度,是否符合吸顶,利用动态class属性设置样式~

window.pageYOffset:距离顶部偏移量
document.documentElement.scrollTop:谷歌浏览器获取滚动条距离顶部的位置
document.body.scrollTop:ie浏览器获取滚动条距离顶部的位置
<template>
  <div class="wrapper">
    <div class="nav-bar" :class="{'is_fixed':isFixed}">  
        这是内容
    </div>
    <div class="scroll">
        这是滚动内容
    </div>
  </div>
</template>
<script>
  export default{
    name:'nav-var',
    data(){
      return{
        isFixed:false
      }
    },
    mounted(){
      window.addEventListener('scroll',this.initHeight)
    },
    methods:{
      initHeight(){
        let scollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
        this.isFixed = scollTop > 152 ? true : false;
      }
    },
    destroyed(){
        window.removeEventListener('scroll',this.initHeight,false)
    }
  }
</script>
<style lang="scss">
.wrapper{
    .nav-bar{
      height:70px;
      line-height: 70px;
      border-top:1px solid gray;
      background: #ffffff;
      &.is_fixed{
        position: fixed;
        top:0;
        width:100%;
        box-shadow: 0 5px 5px #cccccc;
      }
    }
    .scroll{
        height:500px;
    }
}
</style>

用户bPbA4lM
103 声望9 粉丝