还记得之前的博客写到了沉浸状态栏的首页吗?为什么要沉浸状态栏,因为设计师说首页最顶部要放自动滚动的banner,还好微信官方给了一个滑动组件,下面就简单介绍一下吧。
先看看效果
按设计师要求,就是一个banner,但是指示器达不到要求,随手写了个。
官方文档
主要用到了 swiper 组件,详细内容看官方文档
https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html
看看代码
- WXML
<view class="banner">
<swiper class="swiper" autoplay="{{true}}" interval="{{2000 * banners.length}}" duration="{{2000}}"
bindchange="onSwiperChange">
<block wx:for="{{banners}}" wx:key="banners">
<swiper-item>
<van-image width="100%" height="600rpx" src="{{banners[index].src}}" data-index="{{index}}"
bind:click="onClickBanner" />
</swiper-item>
</block>
</swiper>
<view wx:if="{{banners.length>1}}" class="indicator-containrer row-center">
<view class="indicator" wx:for="{{banners}}" wx:key="indicator"
style="width:{{index==currentIdicater?'28':'12'}}rpx;opacity:{{index==currentIdicater?'0.64':'0.32'}};margin-left:{{index==0&&0}}rpx">
</view>
</view>
</view>
东西都没什么,就是要注意下 interval 这个值是整个播放过程的时间。
- WXSS
.banner {
height: 600rpx;
position: relative;
}
.swiper {
width: 100%;
height: 100%;
}
.row-center{
display:flex;
flex-direction:row;
align-items: center;
}
.indicator-containrer {
position: absolute;
bottom: 164rpx;
width: 686rpx;
height: 12rpx;
margin: 0 32rpx;
}
.indicator {
width: 12rpx;
height: 12rpx;
background: #FFFFFF;
border-radius: 6rpx;
opacity: 0.16;
margin-left: 12rpx;
}
样式也简单,就是注意调整一下指示器的位置,我这是按设计图调的。
- Page.js
Component({
...
data:{
...
banners: [],
currentIdicater: 0, // banner的指示器
}
...
methods: {
// 监听页面变化
onSwiperChange(e) {
//e.detail = {current, source}
this.setData({
currentIdicater: e.detail.current
})
},
}
})
代码里面把banner数组加上就行,里面存放图片链接,至于获取数据、数据的格式看需要吧。
结语
banner就这么简单
end
完美撒花