美文网首页
小程序随笔12:swiper实现banner效果

小程序随笔12:swiper实现banner效果

作者: 乌龟学跑步 | 来源:发表于2021-03-17 09:07 被阅读0次

swiper滑块视图容器,官方文档见:https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html

本篇小实例主要实现banner,加载网络图,自适应高度。

实现方法:
1、在小程序页面对应的.wxml文件中,添加代码:

<view>
  <swiper indicator-dots="true" indicator-color="#ffffff" indicator-active-color="#ff0000" autoplay="true"  previous-margin="{{swiperPre}}px" next-margin="{{swiperNext}}px" style="height:{{swiper_img_height}}px">
    <block wx:for="{{dotsources}}" wx:key="*this">
      <swiper-item>
        <image mode="widthFix" src="{{item.img}}" style="width:{{swiper_img_width}}px;height={{swiper_img_height}}px"></image>
      </swiper-item>
    </block>
  </swiper>
</view>

此代码中indicator-dots表示是否显示面板指示点,indicator-color指示点颜色,indicator-active-color当前选中的指示点颜色,autoplay是否自动切换,previous-margin前边距,可用于露出前一项的一小部分,接受 px 和 rpx 值,next-margin后边距,可用于露出后一项的一小部分,接受 px 和 rpx 值,style="height:*px"。
特别注意:
第一:前边距,后边距,异或高度值,使用的时候都要加上单位px或rpx。
第二:此处swiper_img_height和swiper_img_width是代码中算出来的,swiper_img_width根据手机屏宽减去前后边距的值,swiper_img_height根据图片比例算出来的,只把 swiper设置适合高度图片依旧显示不正常。如若图片也显示正常,image同样要设置宽高,如上style属性。

2、在小程序页面对应的.js文件中,添加代码:

Page({
  data: {
    dot sources:[
      img:"http://mmbiz.qpic.cn/sz_mmbiz_png/GEWVeJPFkSHALb0g5rCc4Jf5IqDfdwhWJ43I1IvriaV5uFr9fLAuv3uxHR7DQstbIxhNXFoQEcxGzWwzQUDBd6Q/0?wx_fmt=png",
    },
    {
      img:"http://mmbiz.qpic.cn/sz_mmbiz_jpg/GEWVeJPFkSGqys4ibO2a8L9nnIgH0ibjNXfbicNbZQQYfxxUpmicQglAEYQ2btVXjOhY9gRtSTCxKvAlKFek7sRUFA/0?wx_fmt=jpeg",
    },
    {
      img:"http://mmbiz.qpic.cn/sz_mmbiz_jpg/GEWVeJPFkSH2Eic4Lt0HkZeEN08pWXTticVRgyNGgBVHMJwMtRhmB0hE4m4alSuwsBk3uBBOhdCr91bZlSFbYhFg/0?wx_fmt=jpeg",
    },
    {
      img:"http://mmbiz.qpic.cn/mmbiz_jpg/TcDuyasB5T3Eg34AYwjMw7xbEK2n01ekiaicPiaMInEMTkOQtuv1yke5KziaYF4MLia4IAbxlm0m5NxkibicFg4IZ92EA/0?wx_fmt=jpeg",
    }],
    swiperPre:10,
    swiperNext:10,
    swiper_img_height:0,
    swiper_img_width:0
  },
  onLoad: function (options) {
    wx.getSystemInfo({
      success: (result) => {
        this.data.swiper_img_width = result.windowWidth-this.data.swiperPre-this.data.swiperNext
        this.data.swiper_img_height = this.data.swiper_img_width*0.47
        this.setData({
          swiper_img_height:this.data.swiper_img_height,
          swiper_img_width:this.data.swiper_img_width
        })
      },
    })
  },
})

效果图如下:


swiper效果图

小试牛刀,随笔记录,不喜勿喷。

相关文章

网友评论

      本文标题:小程序随笔12:swiper实现banner效果

      本文链接:https://www.haomeiwen.com/subject/dfrdcltx.html