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
})
},
})
},
})
效果圖如下:

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