在一般的APP头部都有一个标题栏,
有时这个标题栏是不显现的.当页面下滑的时候
这个标题栏就显示出来了
举个例子
去哪儿APP上,景点详情页里.
进去是有一个固定在左上的小圆圈,点击可以返回上一页
当页面下滑时,小圆圈消失,出现了标题栏
下面是html静态页面
<template>
<div>
//这个是小圆圈
<router-link tag="div" to="/" class="header-abs" v-show="showAbs">
<div class="iconfont back-abs-back"></div>
</router-link>
//这个是标题栏
<div class="header-fixed" v-show="!showAbs" :style="opacityStyle">
<router-link to="/">
<div class="iconfont header-fixed-back"></div>
</router-link>
景点详情
</div>
</div>
</template>
<style lang="stylus" scoped>
.header-abs
position absolute
left .2rem
top .2rem
width .8rem
height .8rem
line-height .8rem
border-radius .4rem
text-align center
background: rgba(0, 0, 0, .8)
.back-abs-back
color #ffffff
font-size .4rem
.header-fixed
position fixed
top 0
left 0
right 0
height .84rem
line-height .84rem
text-align center
color #fff
background #333
font-size .32rem
.header-fixed-back
position absolute
top 0
left 0
width .64rem
text-align center
font-size .4rem
color #fff
</style>
如果上图所示
在小圆圈栏和标题栏有两个相反的事件
v-show=“showAbs” 和 v-show="!showAbs"
这两个事件对应的就是显示和消失
为了美观,一般会在显示和消失增加过渡效果
即绑定过渡样式
:style=“opacityStyle”
下面是实现这个过程的方法
<script>
export default {
name: 'DetailHeader',
data () {
return {
//showAbs就是显示和消失的状态,默认是true 即小圆圈显示
showAbs: true,
//过渡效果.默认此时opacity是0
opacityStyle: {
opacity: 0
}
}
},
methods: {
//滑动事件触发
handleScroll () {
//定义此时页面离顶部的距离
const top = document.documentElement.scrollTop
//进行判断
if (top > 60) {
//opacity的值在0到1之间 即显示和消失,为了让这个过程在60-140的距离内完成
let opacity = top / 140
//进行判断 opacity的值大于1是则返回1
opacity = opacity > 1 ? 1 : opacity
this.opacityStyle = { opacity }
//当页面距离顶部60 即小圆圈消失 标题栏显示
this.showAbs = false
} else {
//否则小圆圈显示 标题栏消失
this.showAbs = true
}
}
},
activated () {
//在这个生命周期钩子里,监听页面滚动
//注意这个事件是全局事件,在其他页面进行滚动也会触发这个事件
window.addEventListener('scroll', this.handleScroll)
},
//deacitivated 钩子即是页面关闭触发的事件
deactivated () {
//将这个事件移除 解除绑定
window.removeEventListener('scroll', this.handleScroll)
}
}
</script>
一般的APP都会有这个渐隐显示标题栏的效果.
如果大家有更好的方法,希望能告诉我.