1、打开小程序开发工具,在项目pages下新建mypage文件夹,在文件夹内新建page,名为mypage,并在app.json中将mypage设为第一页面
2、在mypage.wxml中添加代码如下:<swiper autoplay="true" interval="5000" duration="1000"circular="true" ><block wx:for="{{imgUrls}}"><swiper-item><image src="{{item}}" /></swiper-item></block></swiper>添加一个swiper组件,设置自动循环播放
3、在mypage.js添加代码,给图片列表赋值,注意要拷贝三张图到mypage文件夹Page({data: {imgUrls: ['s1.jpg','s2.jpg','s3.jpg'],},})
4、这样能实现滚动显示,但是宽度和高度都是固定的,很不灵活
5、修改mypage.wxml代码如下,动态设置swiper组件的高度:<swiper class = "sw" style = "height:{{imgheights[current]}}px" autoplay="true" interval="5000" duration="1000" circular="true" bindchange='bindchange'><block wx:for="{{imgUrls}}" wx:key="{{index}}"><swiper-item><image src="{{item}}" data-id ="{{index}}"mode="widthFix" bindload="imgload"/></swiper-item></block></swiper>mypage.wxss代码如下:.sw{width: 100%;}image{width: 100%;}
6、在mypage.js文件中动态获取图片实际宽高并根据屏幕尺寸写到swiper的高度,这样实现了自适应,代码如下:Page(撑俯擂摔{data: {imgUrls: ['s1.jpg','s2.jpg','s3.jpg'],imgheights:[],current:0},imgload:function(e){console.log(wx.getSystemInfoSync().windowWidth)var imgheight = e.detail.height;var imgwidth = e.detail.width;var bl = imgheight / imgwidth;var sjgd = bl * (wx.getSystemInfoSync().windowWidth);var hs = this.data.imgheights;console.log(e);console.log(sjgd);hs[e.target.dataset.id] = sjgd;this.setData({imgheights:hs});},bindchange: function (e) {// console.log(e.detail.current)this.setData({ current: e.detail.current })},})
7、编译代码,更改模拟器大尺寸,依然可以自适应了,不过原来这个swiper的设计宽高固定的确实很麻烦