功能需求:不同数组的图片高度不一致,数组内图片高度一致的情况下,动态设置swiper高度
尝试过百度的获取图片高度的方法,发现获取高度不准确,后改用获取设备可视宽度和图片高度的方法解决
动态设置swiper高度的问题
原使用不准确代码:
getElementHeight(element) {
setTimeout(() => {
let query = uni.createSelectorQuery().in(this);
query.select(element).boundingClientRect();
query.exec((res) => {
if (!res) { //如果没获取到,再调一次
this.getElementHeight();
} else {
this.swiperHeight = res[0].height;
console.log(this.swiperHeight)
}
})
}, 80)
},
this.getElementHeight(class类名)
:style="'height:'+swiperHeight+'px'" //高度动态设置样式给swiper组件
----------------获取到的高度不准确,偶尔出现不同图片高度获取是一样的问题
解决方法:
uni.getImageInfo({
src:that.imgIist[0],
success: function(image) {
uni.getSystemInfo({
success: function (res) {
console.log(res)
that.swiperHeight = res.windowWidth/image.width * image.height;
console.log(that.swiperHeight)
}
});
}
});
:style="'height:'+swiperHeight+'px'" //高度动态设置样式给swiper组件
res.windowWidth:屏幕可视宽度
image.width :uni.getImageInfo获取到的图片宽度
image.height :uni.getImageInfo获取到的图片高度
使用uni.getImageInfo 获取的图片宽高是原始宽高 所以需要与设备可视宽度进行等比例计算
此方法不解决数组内的图片高度不一的情况