js/vue 滚动隐藏or显示顶部header

2020-08-19  本文已影响0人  Peter_2B

<template>
   <div>
        <router-link  tag="div" to="/"  class="header-abs"  v-show="showAbs" >返回</router-link>
        <div class="header-fixed" :style="opacityStyle" v-show="!showAbs"> 景点详情 </div>
   </div>
</template>
<script>
export default {
    data(){
      return{
            showAbs:true,
            opacityStyle:{
                opacity:0
            }
        }
    },
    created(){
        window.addEventListener('scroll',this.handleScroll);
    },
    deactivated(){  //因为 ↑是对window绑定的,所以除了该页面,其他页面的滚动也会内存泄露
        window.removeEventListener('scroll',this.handleScroll);
    },
    methods:{
        handleScroll(){
            const top = document.documentElement.scrollTop;
            if(top > 60){
                this.showAbs = false;
                let opacity = top / 140;
                opacity = opacity > 1 ? 1 : opacity;    
                this.opacityStyle={ opacity };
            }else{
                this.showAbs = true;
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.header-abs{
  position: absolute;
  z-index: 10;
  top: 0;
  left: 0;
  width: 35px;
  height: 35px;
  line-height: 35px;
  border-radius: 50%;
  background: rgba(0,0,0,.6);
  text-align: center;
  color:#fff;
  font-size: 12px;
}
.header-fixed{
  width: 100%; 
  height: 40px;
  line-height: 40px;
  background: rgb(34, 97, 180);
  color:#fff;
  text-align: center;
  position: fixed;
  top: 0;
}
</style>
上一篇 下一篇

猜你喜欢

热点阅读