小程序隨筆12:swiper實(shí)現(xiàn)banner效果

swiper滑塊視圖容器,官方文檔見(jiàn):https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html。

本篇小實(shí)例主要實(shí)現(xiàn)banner,加載網(wǎng)絡(luò)圖,自適應(yīng)高度。

實(shí)現(xiàn)方法:
1、在小程序頁(yè)面對(duì)應(yīng)的.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表示是否顯示面板指示點(diǎn),indicator-color指示點(diǎn)顏色,indicator-active-color當(dāng)前選中的指示點(diǎn)顏色,autoplay是否自動(dòng)切換,previous-margin前邊距,可用于露出前一項(xiàng)的一小部分,接受 px 和 rpx 值,next-margin后邊距,可用于露出后一項(xiàng)的一小部分,接受 px 和 rpx 值,style="height:*px"。
特別注意:
第一:前邊距,后邊距,異或高度值,使用的時(shí)候都要加上單位px或rpx。
第二:此處swiper_img_height和swiper_img_width是代碼中算出來(lái)的,swiper_img_width根據(jù)手機(jī)屏寬減去前后邊距的值,swiper_img_height根據(jù)圖片比例算出來(lái)的,只把 swiper設(shè)置適合高度圖片依舊顯示不正常。如若圖片也顯示正常,image同樣要設(shè)置寬高,如上style屬性。

2、在小程序頁(yè)面對(duì)應(yīng)的.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效果圖

小試牛刀,隨筆記錄,不喜勿噴。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容