关于c-s-s:组件吸顶

7次阅读

共计 876 个字符,预计需要花费 3 分钟才能阅读完成。

次要是通过浏览器事件监听函数,判断间隔顶部的高度,是否合乎吸顶,利用动静 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>
正文完
 0