swiper轮播图在小程序中是比较常见的功能,包括:页面顶部产品、活动的内容展示,或者是底部广告推广, swiper ---小程序官方文档解释。
详细见Demo:
1. wxml页面:
<view class="swiperStyle" wx:if="{{showSwiper}}">
<swiper class="swiper-item" indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" circular="{{circular}}" indicator-color="{{indicatorColor}}" indicator-active-color="{{activeColor}}">
<block wx:for="{{adsImgList}}" wx:key="index">
<swiper-item>
<view class="swiper-box"><image src="{{item.adsUrl}}" data-id="{{index}}" bindtap="toAdsLink"></image></view>
</swiper-item>
</block>
</swiper>
</view>
2. js逻辑:
Page({
data: {
imgURL: 'https://xxxx/', //图片地址
showSwiper:true, //控制页面底下的轮播图是否显示
interval: 2000, //自动切换时间间隔
duration: 600, //滑动动画时长
indicatorDots: true, //是否显示面板指示点
autoplay: true, //是否自动切换
circular: true, //是否采用衔接滑动
indicatorColor: "rgba(229,229,229,.3)", //指示点默认颜色
activeColor: "rgba(255,255,255,1)", //指示点选中颜色
adsImgList:[], //获取到的url地址生成数组
},
//把轮播图的显示与控制,写在onShow()里面,这样,每次的页面切换或者默认左上角返回都会调用这个生命周期,比写在onLoad()效果更好
onShow: function () {
let adnubs = 3 //显示的广告位图片张数
const adsInfo = []
for (let i = 0; i < adnubs; i++) {
adsInfo.push({
adsUrl: `${this.data.imgURL}/ads/ads${i + 1}.png`, //获取的是服务器上的图片,也可以改为接口返回的数组
})
}
this.setData({
adsImgList:adsInfo
})
if(adnubs == '1'){ //只有一张广告图的时候,关闭显示指示标
this.setData({
indicatorDots:false
})
}
console.log('广告位数组',this.data.adsImgList)
},
//广告位跳转链接
toAdsLink(e){
var id = e.currentTarget.dataset.id
console.log(id)
if(id == '0'){
wx.navigateTo({
url: `../testPage/testPage`, //更新为要跳转的地址
})
}else if(id == '1'){
wx.navigateTo({
url: `../testPage/testPage`, //更新为要跳转的地址
})
}else if(id == '2'){
wx.navigateTo({
url: `../testPage/testPage`, //更新为要跳转的地址
})
}
},
})
3. wxss样式:(根据实际页面进行调整)
.swiperStyle{
width: 690rpx;
height: 200rpx;
position: fixed;
bottom: 0rpx;
left: 0rpx;
margin: 30rpx;
overflow: hidden;
border-radius: 15rpx;
}
.swiper-item image{
width: 100%;
height: 100%;
}
.swiper-box{
width: 100%;
height: 200rpx;
}