微信小程序轮播图自适应实现

2025-10-20 20:05:25

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的设计宽高固定的确实很麻烦

微信小程序轮播图自适应实现

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
相关推荐
  • 阅读量:188
  • 阅读量:123
  • 阅读量:81
  • 阅读量:72
  • 阅读量:176
  • 猜你喜欢