小程序导航滚动到头部后固定
2020-09-27|HiShop
导读:小程序导航滚动到头部后固定 这也是小程序主界面经常会使用的一种效果,那么如何开发实现,下面为大家解答。...
小程序导航滚动到头部后固定 这也是小程序主界面经常会使用的一种效果,那么如何开发实现,下面为大家解答。
前段代码这里是比较重要的
- <scroll-view scroll-x="true" class="nav {{navFixed? 'positionFixed':''}}" scroll-left="{{navScrollLeft}}" scroll-with-animation="{{true}}">
- <block wx:for="{{navData}}" wx:for-index="idx" wx:for-item="navItem" wx:key="idx">
- <view class="nav-item {{currentNavTab == idx ?'active':''}}" data-current="{{idx}}" bindtap="switchNav">{{navItem.text}}</view>
- </block>
- </scroll-view>
前段整体布局要使用scroll-view
- <scroll-view class="layout" bindscroll='layoutScroll' scroll-y="true" style="height: {{windowHeight}}px;">
- .positionFixed{
- position: fixed;
- left: 0;
- top: 0;
- }
data配置信息看好
- data: {
- adData: ['http://pic.qiantucdn.com/58pic/17/70/72/02U58PICKVg_1024.jpg', 'http://pic2.ooopic.com/12/09/64/46bOOOPICf5_1024.jpg'],
- navData: [
- {
- text: '首页'
- },
- {
- text: '健康'
- },
- {
- text: '情感'
- },
- {
- text: '职场'
- },
- {
- text: '育儿'
- },
- {
- text: '纠纷'
- },
- {
- text: '青葱'
- },
- {
- text: '上课'
- },
- {
- text: '下课'
- }
- ],
- currentNavTab: 0,
- scrollTop: '', //滑动的距离
- navFixed: false, //导航是否固定
onLoad 方法获取宽高
- wx.getSystemInfo({
- success: (res) => {
- this.setData({
- pixelRatio: res.pixelRatio,
- windowHeight: res.windowHeight,
- windowWidth: res.windowWidth
- })
- },
- })
js主要事件
- //导航点击
- switchNav(event) {
- var cur = event.currentTarget.dataset.current;
- //每个tab选项宽度占1/5
- var singleNavWidth = this.data.windowWidth / 5;
- //tab选项居中
- this.setData({
- navScrollLeft: (cur - 2) * singleNavWidth
- })
- if (this.data.currentNavTab == cur) {
- return false;
- } else {
- this.setData({
- currentNavTab: cur
- })
- }
- },
- //监听滑动
- layoutScroll: function (e) {
- this.data.scrollTop = this.data.scrollTop * 1 + e.detail.deltaY * 1;
- console.log(this.data.scrollTop)
- console.log(this.data.navFixed)
- if (this.data.scrollTop <= -342) {
- this.setData({
- navFixed: true
- })
- } else {
- this.setData({
- navFixed: false
- })
- }
- }
以上代码自己完善后即刻达到效果
HiShop小程序工具提供多类型商城/门店小程序制作,可视化编辑 1秒生成5步上线。通过拖拽、拼接模块布局小程序商城页面,所看即所得,只需要美工就能做出精美商城。更多小程序商店请查看:小程序商店