微信小程序自定义标题栏(搜索框)

鄙人小菜鸡,现在需要在标题栏放入一个搜索框,百度搜索结果如下:

做完效果

在需要更改的页面的json文件中加入"navigationStyle": "custom"与using同级

单页面json配置

如果基本上所有页面都需要自定义的话,可以直接在app.json中的window中加入这段代码,表示你需要去掉自带的标题栏。接着就开始自定义标题栏了

在index.wxml中加入

<view>

  <!-- 自定义头部 -->

  <view class='nav bg-white' style='height:{{navH}}px'>

    <view class='nav-title'>

      <view class="INinputheader">

        <icon class="INsearchicon" type="search" size="12"/>

        <input class="weui-input" placeholder="搜索学习内容"/>

      </view>

    </view>

  </view>

  <scroll-view class='bg-gray overflow' style='height:calc(100vh - {{navH}}px)' scroll-y >

    <view class='hidden'>

    </view>

  </scroll-view>

</view>

如果需全局就在app.wxss中加入

/* 自定义顶部栏高度 */

.nav{

  width: 100%;

  overflow: hidden;

  position: relative;

  top: 0;

  left: 0;

  z-index: 10;

}

.nav-title{

  width: 100%;

  height: 45px;

  line-height: 45px;

  text-align: center;

  position: absolute;

  bottom: 0;

  left: 0;

  z-index: 10;

  font-family:PingFang-SC-Medium;

  font-size:36rpx;

  letter-spacing:2px;

}

.nav .back{

  width: 22px;

  height: 22px;

  position: absolute;

  bottom: 0;

  left: 0;

  padding: 10px 15px;

}

.bg-white{

  background-color:rgb(255, 0, 0);

}

.bg-gray{

  background-color: #f7f7f7;

}

.overflow{

  overflow: auto;

}

.hidden{

  overflow: hidden;

}

.INinputheader{

  width:60%;

  height:30px;

  background:rgba(255,255,255,1);

  border-radius:30px;

  font-size: 14px;

  margin-top:7px;

  position: relative; 

  float: left;

  margin-left:12px;

}

.INsearchicon{

  position: absolute;

  left:12px;

}

.weui-input{

  height: 30px;

  line-height: 30px;

  text-align: left; 

  padding-left: 30px;

  letter-spacing:0px;

}

.INtab{

  text-align: left;

  margin-left: 12px;

  color: #fff;

}

ok,wxml和wxss都写好了,因为手机各有差异,为了适配各种手机的顶部,常规的我们就需要获取标题栏的高度以此实现动态绑定高度,为了预防onLoad有时候不触发,我们直接在app.js的onLaunch的函数中加入代码:

 // 获取顶部栏信息

     wx.getSystemInfo({

      success: res => {

        //导航高度

        this.globalData.navHeight = res.statusBarHeight + 46;

      }, fail(err) {

        console.log(err);

      }

    })

直接获取高度,存放在与onLaunch同级的

globalData:{

    userInfo:null,

    navHeight:0

  },

中,这个存放全局数据。接着,在需要使用的页面的js文件中先获取app,加入代码

const App = getApp();//设立顶部栏高度

获取到App实例,在onLoad中把获取到的存在data中即可在wxml中动态绑定使用

onLoad: function (options) {

    //自定义头部方法

    this.setData({

      navH: App.globalData.navHeight

    });

  },

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。