本文实例为大家分享了微信小程序实现轮播图的具体代码,供大家参考,具体内容如下
1、wxss样式:
.showTableBox {
position: relative;
width: 100%;
height: 180px;
overflow: hidden;
}
.slideshowImgBox {
position: absolute;
z-index: 1;
width: 500%;
height: 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组件,使用也是很方便的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。