这次我主要想总结一下微信小程序实现上下滚动消息提醒,主要是利用swiper组件来实现,swiper组件在小程序中是滑块视图容器。
我们通过vertical属性(默认为false,实现默认左右滚动)设置为true来实现上下滚动。
(需要注意的是:只要你的swiper存在vertical属性,无论你给值为true或者false或者不设参数值,都将实现上下滚动)
wxml
<swiper class="swiper_container_notice swiper_container" vertical="true" autoplay="true" circular="true" interval="2000"> <block wx:for="{{msgList}}" wx:if="{{item.id}}"> <swiper-item bindtap="messageDetails" data-id="{{item.id}}" class="swiper_notice swiper"> <image class="van-notice-bar__left-icon_notice" src="/assets/images/message.png"></image> <view class="swiper_item_notice swiper_item" data-id="{{item.id}}">{{item.title}}</view> </swiper-item> </block> </swiper> </view>
js
messageDetails(e){ wx.navigateTo({ url: '/pages/setting/protocol/splAgreement/index' }) },
var app = getApp() Page({ data: { }, onLoad(e) { console.log(e.title) this.setData({ msgList: [ { url: "url", title: "公告:多地首套房贷利率上浮 热点城市渐迎零折扣时代" }, { url: "url", title: "公告:悦如公寓三周年生日趴邀你免费吃喝欢唱" }, { url: "url", title: "公告:你想和一群有志青年一起过生日嘛?" }] }); } })
wxss
.swiper_container { height: 55rpx; position: absolute; bottom: 0; 100%; color: #fff; } .swiper_item_notice { font-size: 25rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; letter-spacing: 2px; } .swiper_notice{ display: flex !important; align-items: center !important; padding-left: 20rpx !important; } .swiper_notice image{ 35rpx; height: 35rpx; margin-right:10rpx; margin-right: 40rpx; }
从轮播页面切换到其他页面,在跳转回来的时候,会涉及到不更新swiper导致不显示或显示问题的解决办法
添加 current="{{current}}"
<swiper current="{{current}}" class="swiper_container_notice swiper_container" vertical="true" autoplay="true" circular="true" interval="2000"> <block wx:for="{{msgList}}" wx:if="{{item.id}}"> <swiper-item current="{{current}}" bindtap="messageDetails" data-id="{{item.id}}" class="swiper_notice swiper"> <image class="van-notice-bar__left-icon_notice" src="/assets/images/message.png"></image> <view class="swiper_item_notice swiper_item" data-id="{{item.id}}">{{item.title}}</view> </swiper-item> </block> </swiper>
js current设置为0
data: { current:0, } 获取轮播数据 this.setData({ msgList:[res] },()=>{ this.setData({ current: 0 }) })