Vue实现页面顶端粘带效果

    xiaoxiao2023-11-15  150

    Vue  实现页面顶端粘带效果

          现在在做App的时候都要用到页面粘带效果,主要是用于在滑动页面时,某个组件到达顶端时,将此组件固定在顶端,效果如下图所示。(自己画的图,不好看请见谅!)

       简述:页面滑动,头部向上滑动,当绿色部分滑动到顶端时,绿色部分固定在顶端,内容部分继续滑动。

       

       完整例子代码:

             

    <template> <div class="wrap" id="wrap"> <div class="header"> <div>头部部分的内容</div> <div>头部部分的内容</div> <div>头部部分的内容</div> <div>头部部分的内容</div> </div> <div class="content" :class=""{stick:show}">需要固定的部分</div> <div class="dliver" :style="{display:show? 'block':'none'}"></div> //加一个这个目的,主要是为了固定和还原时更流畅。 <div class="context"> <div v-for="item in 30"> This is item{{item}} </div> </div> </div> </template> <script> export default { data () { return { show:false } }, methods: { GetHeight(){ const scroll_height= document.documentElement.scrollTop || document.body.scrollTop;//获取到滚动的高度 const head=""; head= document.getElementsByClassName('header')[0].offsetHeight//获取到头部的高度 scrolled >= head? this.show=true : this.show=false console.log('滚动距离:'+scroll_height,'头部高度:'+ head); } }, mounted(){ this.$nextTick(()=> { window.addEventListener('scroll', this.GetHeight,true) }) }, destroyed () { this.$nextTick( () => {//离开页面销毁 window.removeEventListener('scroll', this.GetHeight) }); } } </script> <style scoped> .header{ background-color:red; } .content{ height:100px; background-color: blue; text-align: center; } .stick{ position: fixed; top: 0; z-index:0; width: 100%; } .context{ background-color: yellow; padding: 8px; } </style>

     

       亲测有效!

     

         

    最新回复(0)