微信小程序中使用 swiper 组件可以实现图片轮播效果,但是默认 swiper 高度是固定的 150px,如果项目中图片大于固定高度就会被隐藏,所以本篇文章要实现轮播图片的高度自适应。
1.以最高的图片为基准(需要考虑图片全部一样的大小) 关于小程序轮播图自适应的问题,目前网上的资料不少,但是都是目前这种,不会随着图片的高度去变化。会以最高的一张图片高度为基准。正常的需求应该都能满足,但是现在的需求是需要随着图片的高度去改变。所以有了第二点。 代码语言:javascript复制
代码语言:javascript复制Page({
data: {
imgUrls: ["img/1.jpg", "img/2.jpg", "img/3.jpg"],
indicatordots: true, //是否显示面板指示点
autoplay: true, //是否自动切换
interval: 5000, //自动切换时间间隔
duration: 500, //滑动动画时长
color: "#ffffff", //当前选中的指示点颜色
swiperHeight: "", //swiper高度
},
goheight: function (e) {
var width = wx.getSystemInfoSync().windowWidth;
//获取可使用窗口宽度
var imgheight = e.detail.height;
//获取图片实际高度
var imgwidth = e.detail.width;
//获取图片实际宽度
var height = (width * imgheight) / imgwidth + "px";
//计算等比swiper高度
this.setData({
swiperHeight: height,
});
},
});2.以当前图片的高度为基准(完美实现) 动态轮播图高度.gif代码语言:javascript复制
//bindload是绑定图片加载的事件,记得给image加上mode=“widthFix”这个属性哦,
//还有就是设置这个image 100%宽度 //getswiperImgH
中打印的图片的src发现顺序有时和图片真实的顺序是不一致,故加了一个参数index保证顺序一致。
代码语言:javascript复制Page({
data: {
imgUrls: [
"https://img3.doubanio.com/view/photo/l/public/p2494946035.webp",
"http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg",
"http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg",
"http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg",
],
imgheights: [],
swiperCurrent: 0,
},
bindchange: function (e) {
this.setData({
swiperCurrent: e.detail.current,
});
},
getswiperImgH(e) {
//获取当前屏幕的宽度
let winWid = wx.getSystemInfoSync().windowWidth;
//图片高度
let imgh = e.detail.height;
//图片宽度
let imgw = e.detail.width;
//计算的高度值
let swiperH = (winWid * imgh) / imgw + "px";
let imgheights = this.imgheights;
//把每一张图片的高度记录到数组里
imgheights[e.currentTarget.dataset.index] = swiperH;
this.setData({
imgheights: imgheights,
});
},
});
|