小程序轮播图
<swiper indicator-dots="{{indicatorDots}}" indicator-color="{{indicatorColor}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" indicator-active-color="{{bg}}" style='height:{{Height}}'> <block wx:for="{{imgUrls}}"> <swiper-item> <image src="{{item}}" class="slide-image" mode="widthFix" bindload='imgHeight'/> </swiper-item> </block> </swiper>
index.js
Page({ data: { imgUrls: [ '/img/ban1.jpg', '/img/ban2.jpg', '/img/ban3.jpg' ], indicatorDots: true, //是否显示面板指示点 indicatorColor:'#ffa700', autoplay: true, interval: 5000, duration: 1300, bg: '#fff', Height: "" }, imgHeight: function (e) { var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度 var imgh = e.detail.height;//图片高度 var imgw = e.detail.width;//图片宽度 var swiperH = winWid * imgh / imgw + "px" this.setData({ Height: swiperH//设置高度 }) } })
图片高度随宽度自适应
还有另一种wxss的方法
假设图片原尺寸为1000*500,则只需给swiper的高设置为375rpx即可
(以iphone6为参考,其宽为750,所以750*500/1000,即只需要设置swiper的宽高比等于图片的宽高比)
WXSS
在底层支持新的尺寸单位 rpx
,开发者可以免去换算的烦恼,只要交给小程序底层来换算即可
代码如下:
index.wxml
<swiper indicator-dots="{{indicatorDots}}" indicator-color="{{indicatorColor}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" indicator-active-color="{{bg}}" > <block wx:for="{{imgUrls}}"> <swiper-item> <image src="{{item}}" class="slide-image" mode="widthFix" bindload='imgHeight'/> </swiper-item> </block> </swiper>
index.wxss
swiper{ height:375rpx; } image{ display: block; width:100%; }
index.js
Page({ data: { imgUrls: [ '/img/ban1.jpg', '/img/ban2.jpg', '/img/ban3.jpg' ], indicatorDots: true, //是否显示面板指示点 indicatorColor:'#ffa700', indicatorActiveColor:"#333333", autoplay: true, interval: 5000, duration: 1300, } })
mode:图片裁剪、缩放的模式。详情参考:https://developers.weixin.qq.com/miniprogram/dev/component/image.html
更多swiper参考文档:https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html