微信小程序之轮播图实现

网页及移动设备可以轮播图来实现滑动查看图片的效果,在微信小程序中使用swiper组件实现,具体介绍可查看官方文档https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html

首先先放上我实现的效果(觉得还挺好看哈哈)

接着放上wxml代码,这里定义了轮播图下方圆点的颜色及选中时的颜色,可以根据自己的需要进行设置,中间的swiper组件即可放置轮播图中的图片,需要设置宽度等

<!--index.wxml-->
<swiper  indicator-dots="{{indicatorDots}}"  autoplay="{{autoplay}}" style="height:{{height}}px;" interval="{{interval}}" duration="{{duration}}" circular="true" indicator-color="yellow" indicator-active-color="red">  
  <block wx:for="{{imgData}}" wx:key="{{index}}">  
   <swiper-item>   
  <image src='{{item}}' class="slide-image" mode="widthFix" bindload='setContainerHeight' style='width:100%'/>  
 </swiper-item>  
</block>  
</swiper>

这是wxss代码,定义了布局方式及宽高等,在这里由于之前设置的时候图像不能全部铺满屏幕,所以将宽度设置成120%,这样子就好了

/**index.wxss**/
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #aaa;
}

.usermotto {
  margin-top: 200px;
}
swiper-item{
  width:120%;
  height: auto;
  display: block;
}

这是js代码,将图片放置在images文件夹内,定义为imgData,接着就可以通过触发事件来实现轮播图片切换了,这里注意一点,这里使用的是相对宽高度,及比较图片的原始宽高度与屏幕的宽高,而不是直接放置图片的宽高,这样也更能在不同的手机设备上匹配。

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    imgData: [
      "/images/1.png",
      "/images/2.png",
      "/images/3.png",
      "/images/4.png"
    ],
    indicatorDots: true,  //小点
    autoplay: false,  //是否自动轮播
    interval: 3000,  //间隔时间
    duration: 3000,  //滑动时间
    height: 0
  },
  //轮播图的切换事件
  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  //点击指示点切换
  chuangEvent: function (e) {
    this.setData({
      swiperCurrent: e.currentTarget.id
    })
  },
  //设置轮播容器的高度
  setContainerHeight: function (e) {

    //图片的原始宽度
    var imgWidth = e.detail.width;

    //图片的原始高度
    var imgHeight = e.detail.height;

    //同步获取设备宽度
    var sysInfo = wx.getSystemInfoSync();
    console.log("sysInfo:", sysInfo);

    //获取屏幕的宽度
    var screenWidth = sysInfo.screenWidth;

    //获取屏幕和原图的比例
    var scale = screenWidth / imgWidth;

    //设置容器的高度
    this.setData({
      height: imgHeight * scale
    })
    console.log(this.data.height);
  },
  //点击图片触发事件
  swipclick: function (e) {
    console.log(this.data.swiperCurrent);
    wx.switchTab({
      url: this.data.links[this.data.swiperCurrent]
    })
  }
})

有了这些代码,大家可以实际操作起来啦

最后欢迎大家点击我的小程序,不止有轮播图哦~

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值