本文实例为大家分享了微信小程序实现轮播图的具体代码,供大家参考,具体内容如下
1、wxss样式:
/* 页面显示图片的框 */
.showTableBox {
position: relative;
width: 100%;
height: 180px;
overflow: hidden;
}
/* img图片所在的父元素盒子,有几张img,width就设置百分之几百 */
.slideshowImgBox {
position: absolute;
z-index: 1;
width: 500%;
height: 100%;
}
/* img width设置为: 100% / 图片总数 的百分比 */
.slideshowImgBox image {
width: 20%;
height: 100%;
float: left;
}
/* 下方小圆点样式*/
.circleBox {
width: 100%;
position: absolute;
bottom: 10px;
justify-content: center;
}
.circle {
width: 5px;
height: 5px;
border-radius: 50%;
background-color: #F5F5F5;
margin: 0 5px;
z-index: 999;
}
.circleActive {
background-color: #BF360C;
}
其实到这里适配就完成啦,下面是怎么手写一个轮播图哈哈
2、js代码:
page({
data: {
leftNum: 0,//type为number的偏移量,方便计算
imgLeft: "0", //偏移量,
screenWidth: 0, //屏幕width
changCircleIndex: 0, //对应圆球的下标,css根据页面下标显示对应class
slideshowImgs: ["../images/beiJing.jpg", "../images/chengDu.jpg",
"../images/shangHai.jpg", "../images/chongQing.jpg", "../images/beiJing.jpg"
],
},
onLoad: function (options) {
this.setData({
screenWidth: wx.getSystemInfoSync().windowWidth //获取屏幕宽度
})
this.imageCarousel()
},
imageCarousel: function () {
let imgOverallWidth = this.data.screenWidth * (this.data.slideshowImgs.length - 1)
let timer = setInterval(() => {
this.data.imgLeft = `${this.data.leftNum -= this.data.screenWidth}px`
this.setData({
imgLeft: this.data.imgLeft,
changCircleIndex: -(this.data.leftNum / this.data.screenWidth)
})
if (this.data.leftNum === -imgOverallWidth) {
this.setData({
changCircleIndex: 0,
leftNum: 0,
imgLeft: `${this.data.leftNum}px`
})
}
}, 3000)
},
})
3、wxml代码:
<view class="photo">
<view class="photoFixedBox">
<view class="showTableBox">
<view class="slideshowImgBox" style="left:{{imgLeft}};">
<!--这里列表渲染的图片一共五张,第一张和最后一张是同一张图,防止轮播时出现白屏 -->
<image wx:for="{{slideshowImgs}}" src="{{item}}"></image>
</view>
<view class="circleBox flex">
<!-- {{changCircleIndex === index ? 'circleActive' : ''}}"是动态class,根据index来改变圆点颜色 -->
<view wx:for="{{slideshowImgs.length-1}}" class="circle {{changCircleIndex === index ? 'circleActive' : ''}}"></view>
</view>
</view>
<view class="photoClassifyBigBOx">
<view class="imgClassifyBox flex" wx:for="{{imgClassify}}"><text>{{item}}</text></view>
</view>
</view>
</view>
以上就是整个轮播图的实现啦,圆点的变色显示index根据图片left的偏移量距离来计算:偏移量 / 显示框的宽度,
其实微信小程序有swiper组件,使用也是很方便的。