我這邊開(kāi)發(fā)用的是 wepy精耐,代碼風(fēng)格跟小程序原生的不太一樣狼速,下面代碼是依照小程序的代碼風(fēng)格整理之后的,可能有不同或遺漏的地方卦停,但這都不重要,注意領(lǐng)會(huì)精神惊完!
原理:
- 獲取設(shè)備寬度
- 獲取 swiper 內(nèi)的圖片寬高,計(jì)算寬高比
- 根據(jù)寬高比計(jì)算出圖片寬度100%(屏幕寬度)時(shí)圖片的高度 imgHeight
- 由于多張圖片可能高度不一致小槐,所以將所有的 imgHeight 放入一個(gè)數(shù)組,swiper 滑動(dòng)時(shí)就將當(dāng)前圖片的 imgHeight 賦值給 swiper件豌。
// wxml
<swiper class="swiper" indicator-dots="true" circular="true" bindchange="bindchange" style="height:{{imgsHeight[current]}}px;">
<block wx:for="{{imgUrls}}" wx:key="{{index}}">
<swiper-item class="swiper_item">
<image src="{{item.url}}" class="slide_image" data-id="{{index}}" mode="aspectFill" bindload="imageLoad" />
</swiper-item>
</block>
</swiper>
// js
data: {
windowWidth: 0,
imgUrls: [...],
imgsHeight: [],
current: 0,
imgWidth: 750
}
// 每張圖片加載完成會(huì)執(zhí)行 imageload 方法
imageLoad: function(e) {
// 獲取圖片寬高比
const ratio = e.detail.width / e.detail.height
// 按照寬高比計(jì)算圖片寬度 100% 時(shí)的高度
const imgHeight = this.windowWidth / ratio
// 把每一張圖片對(duì)應(yīng)的高度記錄到 imgsHeight 數(shù)組里
this.imgsHeight[e.target.dataset.id] = imgHeight
},
// swiper 綁定 bindchange 函數(shù)控嗜,用來(lái)獲取 current 值茧彤,傳入 data
bindchange: function(e) {
this.setData({
current: e.detail.current
})
}
onLoad() {
// 獲取設(shè)備屏幕寬度
wx.getSystemInfo({
success: (res) => {
this.windowWidth = res.windowWidth
}
})
}
// wxss
.swiper image {
width: 100%;
height: 100%;
}