先效果图:
一开始导航栏是透明的,页面拉下去后变成非透明。
1.首先怎么把导航栏变透明
https://uniapp.dcloud.io/collocation/pages?id=style
其中有关导航栏的只有这几条:
看到第一条,改颜色,就是这个啦。
但是要注意一点,page.json中还有全局的修改(https://uniapp.dcloud.io/collocation/pages?id=globalStyle)。因为一般应用有需要导航栏的页面,也有不需要导航栏的页面。一般不需要导航栏的页面多,因此会在全局设置中,把navigationStyle设置成custom。因此设单独页面的导航栏时候,要在单独页面设置navigationStyle为default。
{
"path": "pages/device/detail/index",
"style":
{
"navigationStyle": "default", // 如果全局设了navigationStyle=custom就要加这个
"navigationBarBackgroundColor": "#FF6363",
"navigationBarTextStyle": "white"
}
}
那怎么让他透明呢?
首先,不能用#00000000这种透明,也不能用transparent(古老版本可以),因为文档中更新了类型必须为HexColor,HexColor只有6位,因此不支持透明,文字transparent自然也不行了。
因此只能用app-plus,这里有一个坑,加了这个以后,就默认你是使用导航栏了,也就相当于默认写了个"navigationStyle": “default”,就会顶掉全局的了。另外,也会使得navigationBarBackgroundColor失效。
app-plus.titleNView.backgroundColor中的入参是string,并且支持rgba,因此就可以透明啦。
最终代码:
{
"path" : "pages/device/detail/index",
"style" :
{
"navigationBarTextStyle": "white",
"app-plus": {
"titleNView": {
"type": "float",
"backgroundColor":"rgba(0,0,0,0)",
}
}
}
}
至此就实现了透明
怎么让滑动的时候不透明呢?
首先确定变化的时机,是页面拖动到起始不是0的时候,这里uniapp有个生命周期onPageScroll可以监控(https://uniapp.dcloud.io/collocation/frame/lifecycle?id=%e9%a1%b5%e9%9d%a2%e7%94%9f%e5%91%bd%e5%91%a8%e6%9c%9f)
再看app-plus的文档(https://uniapp.dcloud.io/collocation/pages?id=app-plus)经过在文档里嵌套好几层的跳转,跳到了这个页面(https://www.html5plus.org/doc/zh_cn/webview.html#plus.webview.WebviewTitleNViewStyles),其中有些属性可以动态修改,也有为了修改而暴露出的方法。
接下来不写分析了,太长,直接上最终代码:
在页面中的script加上:一个生命周期
onPageScroll(e) {
if(e.scrollTop===0){
this.$mp.page.$getAppWebview().setStyle({titleNView:{backgroundColor:'#00000000'}})
}else{
this.$mp.page.$getAppWebview().setStyle({titleNView:{backgroundColor:'#0C54A3'}})
}
},
就可以实现拉下来的时候不透明,最上方的时候透明了
- 5-31 另一个项目中又用了一次这个,因此把这个提出成一个mixin,下次再用page.json中配置完以后直接引入就行了,方便一点。
- 6-02 1、新增了参数来控制滑动到多少的时候才变,原来是不为0就变。2、新增了一个变量来记录是否位于范围,防止一直滚动页面的时候一直设相同的导航栏样式,浪费资源(不知道是否会浪费资源,做最坏的打算,所以先写上)
页面demo:
<template>
<view class="test">
detail
</view>
</template>
<script>
import { navigationScrollMixins } from "@/component/navigationScrollMixins.js";
export default {
mixins: [navigationScrollMixins],
// navigationScrollMixinsFlag: 160, // 利用Mixin的替代规则:这个加了就按这个,没加就按Mixin里设定的
}
</script>
<style scoped>
.test{
background-color: red;
height: 150%;
}
</style>
navigationScrollMixins.js:
export const navigationScrollMixins = {
onPageScroll(e) {
if(this.scrollAtRange && (e.scrollTop > this.navigationScrollMixinsFlag)){
this.$mp.page.$getAppWebview().setStyle({titleNView:{backgroundColor:'#0C54A3'}})
this.scrollAtRange = false
}
if(!this.scrollAtRange && (e.scrollTop < this.navigationScrollMixinsFlag)){
this.$mp.page.$getAppWebview().setStyle({titleNView:{backgroundColor:'#00000000'}})
this.scrollAtRange = true
}
},
data() {
return{
scrollAtRange: true, // 记录是否位于范围,防止一直滚动页面的时候一直设相同的导航栏样式,浪费资源
navigationScrollMixinsFlag : 0,
}
}
}