需求分析
微信小程序开发,经常遇到类似tabBar的页面切换效果:视图中有标题和页面,当点击一个标题时,该标题呈选中状态,页面自动切换;当滑动页面时,标题自动切换。
实现逻辑
这种效果的实现逻辑是:定义变量selectedTitle、标题的id,当id和selectedTitle相等时,定义样式title-selected。当点击一个标题时,将该标题的id赋值给selectedTitle,该标题获得样式title-selected,呈现选中状态。页面使用swiper组件,将current属性与selectedTitle绑定,可以实现页面自动切换。将current赋值给selectedTitle,当滑动页面时,标题将自动切换。
项目源码
页面切换-横向的代码如下。
1、JS文件
data: { // 定义标题的数组 titles: ["Yellow", "Orange", "Green", "Blue", "Purple"], // 定义选中标题的初始值0 selectedTitle: "0", }, // 定义点击标题的事件处理函数,将选中标题的id赋值给selectedTitle bindtap: function (e) { console.log(e) this.setData({ selectedTitle: e.currentTarget.id }); }, //定义滑块改变的事件处理函数,将current赋值给selectedTitle bindChange: function (e) { this.setData({ selectedTitle: e.detail.current }) }, onReady: function () { // 页面渲染完成 var that = this; wx.getSystemInfo({ success: function (res) { that.setData({ swiperHeight: (res.windowHeight - 37) }); } }) }
需求分析
实现逻辑
项目源码页面切换-横向的代码如下。 1、JS文件data: { // 定义标题的数组 titles: ["Yellow", "Orange", "Green", "Blue", "Purple"], // 定义选中标题的初始值0 selectedTitle: "0", }, // 定义点击标题的事件处理函数,将选中标题的id赋值给selectedTitle bindtap: function (e) { console.log(e) this.setData({ selectedTitle: e.currentTarget.id }); }, //定义滑块改变的事件处理函数,将current赋值给selectedTitle bindChange: function (e) { this.setData({ selectedTitle: e.detail.current }) }, onReady: function () { // 页面渲染完成 var that = this; wx.getSystemInfo({ success: function (res) { that.setData({ swiperHeight: (res.windowHeight - 37) }); } }) } 2、WXML文件<view class="titles"> <!--绑定事件处理函数bindtap--> <!--给选中的组件,即数组当前项的下标与selectedTitle相等的组件,定义样式名titles-selected--> <block wx:for="{{titles}}"> <view id="{{index}}" bindtap="bindtap" class="title {{index==selectedTitle ? 'title-selected' : ''}}"> {{item}} </view> </block> </view> <!--绑定事件处理函数bindchange--> <swiper bindchange="bindChange" current='{{selectedTitle}}' style="height:{{swiperHeight}}px"> <block wx:for="{{titles}}"> <swiper-item> <!--设置5个样式名--> <view class='page bc_{{item}}'>{{item}}</view> </swiper-item> </block> </swiper> 3、WXSS文件.titles { height: 36px; width: 750rpx; background-color: lightgray; display: flex; justify-content: space-around; } .title { width: 180rpx; display: flex; align-items: center; justify-content: center; } .title-selected { border-bottom: 2px solid red; color: red; } .page { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 90rpx; color: white; } .bc_Yellow { background-color: yellow; } .bc_Orange { background-color: orange; } .bc_Green { background-color: green; } .bc_Blue { background-color: blue; } .bc_Purple { background-color: purple; } 作者:天下雪 |