JavaScript

超轻量级php框架startmvc

微信小程序实现滑动切换自定义页码的方法分析

更新时间:2020-08-10 10:42:01 作者:startmvc
本文实例讲述了微信小程序实现滑动切换自定义页码的方法。分享给大家供大家参考,具体

本文实例讲述了微信小程序实现滑动切换自定义页码的方法。分享给大家供大家参考,具体如下:

效果如下:

这里三个图片使用了swiper组件进行轮播,下方的页码数字1、2、3会随着图片的切换变动位置

在微信小程序中我们是无法操作dom的,那么


var div = document.getElementById('id');
div.setAttribute("class", "className");

这种方式实现。

然后我们可以考虑使用hidden或者wx:if的方式,将三个页码显示的view进行轮流显示/隐藏操作。但是不知道为什么这种方式只支持一次操作

最后,使用了display:none/block来达到影藏/显示状态的切换,这个display是写在wxml文件中的


 <view class="bottomView" >
 <view class="bottom1" style="display:{{bottomHidden1}}" >
 <view class="pageCur">
 <text class="textPageCur textFont">{{index+1}}-5</text> //index是因为上方采用了<block wx:for="{{itemInfor}}" >显示内容,index从0开始计数便是当前下标
 </view>
 <view class="buttomImg">
 <image clss="horImg" mode="top left" src="../img/horizontal.jpg"></image>
 </view>
 </view>
 <view class="bottom2" style="display:{{bottomHidden2}}">
 <view class="pageCur">
 <text class="textPageCur textFont" > {{index+1}}-5</text>
 </view>
 <view class="buttomImg">
 <image clss="horImg" mode="top left" src="../img/horizontal.jpg"></image>
 </view>
 </view>
 <view class="bottom3" style="display:{{bottomHidden3}}">
 <view class="pageCur">
 <text class="textPageCur textFont">{{index+1}}-5</text>
 </view>
 <view class="buttomImg">
 <image clss="horImg" mode="top left" src="../img/horizontal.jpg"></image>
 </view>
 </view>
 </view>

以上这就是页码显示部分,页码的组成包括一个text和一个image(下方白色横线),这个内容嵌套在<swiper-item></swiper-item>

bottomView采用position:fixed的定位方式固定在底部设置高和宽,bottom3、2、1采用position:absolute的方式。需要注意的是,如果在bottomView使用了display:flex,将无法使用position。所以在这一部分未采用flex。但是上面的文字和图片部分采用的是display:flex实现的,这种方式比较简单

在swiper中,绑定了bindchange="swiperChange"方法,用于在页面切换时触发下方页码的变化动作,在js文件中该方法如下:


Page({
 data: {
 bottomHidden1:"block",
 bottomHidden2: "none" ,
 bottomHidden3: "none" ,
 },
 swiperChange:function(event){
 var currentView=event.detail.current; //此处使用了swiper的bindchange事件带过来的参数current,这个参数从0开始计数,内容为当前页码
 var isHidden1 ="";
 var isHidden2 ="";
 var isHidden3 ="";
 switch (currentView) {
 case 1:
 isHidden1 = "none";
 isHidden2 = "block";
 isHidden3 = "none";
 break;
 case 2:
 isHidden1 = "none";
 isHidden2 = "none";
 isHidden3 = "block" ;
 break;
 case 0:
 isHidden1 = "block";
 isHidden2 = "none";
 isHidden3 = "none";;
 break;
 }
 this.setData({
 bottomHidden1:isHidden1,
 bottomHidden2: isHidden2,
 bottomHidden3: isHidden3
 });
 },

希望本文所述对大家微信小程序开发有所帮助。

微信小程序 滑动切换 自定义页码