微信小程序点击tabbar,tabbar跟随移动

WeChat_20231221145125

1. 简单页面布局代码

<view class="selectTabs">
  <scroll-view style="width: 100%;" class="select_title" scroll-x scroll-left="{{scrollLeft}}" scroll-with-animation="true" scroll-into-view="{{bankcode}}">
    <view 
    wx:for="{{cityList}}"
    wx:key="index"
    class="title_item {{item.id==cityid?'active':''}}"
    bindtap="handleItemTap"
    id="{{item.id}}"
    >
    {{item.name}}
    </view>
  </scroll-view>
  <view class="select_content">
    <slot></slot>
  </view>
</view>

2. 页面样式

.select_title{
  height: 80rpx;
  white-space: nowrap;
}
.title_item{
  margin: 15rpx 0 0 0rpx;
  display: inline-block;
  padding: 10rpx 20rpx;
  border-radius: 15rpx;
  background-color: #eeeeee;
  margin-right: 20rpx;
  font-size: 30rpx;
  color: #F53C28;
}
.active{
  background-color: #F53C28;
  color: white;
  border-radius: 15rpx;
}

3. js文件

通过const app = getApp()获取定义的当前设备的屏幕宽度safeWidth

// pages/tabbar/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollLeft:0,
    safeWidth:app.globalData.safeWidth,
    cityid:1,
    cityList:[
      {
        name:'南宁',
        id:1
      },
      {
        name:'柳州',
        id:2
      },
      {
        name:'广州',
        id:3
      },
      {
        name:'深圳',
        id:4
      },
      {
        name:'北京',
        id:5
      },
      {
        name:'上海',
        id:6
      },
      {
        name:'杭州',
        id:7
      }
    ]
  },
  
    handleItemTap(e){
      const ids = e.currentTarget.id;
      const Left = e.currentTarget.offsetLeft - (this.data.safeWidth * 0.8)/2
      this.setData({
        scrollLeft:Left,
        cityid:ids
      })
    },


4. app.js文件

根据wx.getSystemInfoSync().safeArea.width获取设备的屏幕宽度,定义为全局变量,方便调用

App({
  onLaunch() {
    this.globalData.safeWidth = wx.getSystemInfoSync().safeArea.width
    
  },
  globalData: {
    safeWidth:0
  }
})
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值