需求: 轮播图的高度和图片的高度是一致的,轮播图的高度一般默认150px;
问题: 图片的高度如何获取;*width->widthFix->height;
那么如何去获取一张网络图片的高度:
1.请求轮播图的数据[];
2.image src="url字符串";
3.图片加载完成。
示例如下:
// xx.js
import queryRect from '../../utils/query-rect'
data: {
swiperHeight: 0
},
const throttleQueryRect = throttle(queryRect, 1000)
handleSwiperImageLoaded: function() {
// 获取图片的高度(如果去获取某一个组件的高度)
throttleQueryRect(".swiper-image").then(res => {
const rect = res[0]
this.setData({ swiperHeight: rect.height })
})
},
// xx.wxml
<!-- 轮播图 -->
<swiper class="swiper"
indicator-dots
autoplay
circular
style="height: {{swiperHeight}}px;"
>
<block wx:for="{{banners}}" wx:key="bannerId">
<swiper-item class="swiper-item">
<image class="swiper-image"
src="{{item.pic}}"
mode="widthFix"
bindload="handleSwiperImageLoaded"></image>
</swiper-item>
</block>
</swiper>
// xx.wxss
/* 轮播图样式 */
.swiper-item {
display: flex;
}
.swiper-item .swiper-image {
width: 100%;
}
// query-rect.js
export default function (selector) {
return new Promise((resolve) => {
const query = wx.createSelectorQuery()
query.select(selector).boundingClientRect()
// query.exec(resolve)
query.exec((res) => {
resolve(res)
})
})
}