最近做小程序项目,需要做一个通知公告栏,使用的UI组件里没有这给组件,自能自己手撸一个勉强使用。
两个相同的text 拼接滚动,可避免infinite的影响无缝衔接的滚动效果。
wxml
<view class="notice">
<view class="left"><view>通知公告</view></view>
<view class="right scrollx">
<view class="notice-text-box">
// 双text 避免 text 滚动到最后文本空白
<text class="notice-text {{ismove? 'animte-move':''}}" style='--width--:{{-width}}px; --time--:{{time}}'>
<text wx:for="{{noticeList}}" wx:for-index="index" wx:key="index">{{item.noticeContent}}</text>
</text>
<text class="notice-text {{ismove? 'animte-move':''}}" style='--width--:{{-width}}px; --time--:{{time}}'>
<text wx:for="{{noticeList}}" wx:for-index="index" wx:key="index">{{item.noticeContent}}</text>
</text>
</view>
</view>
</view>
wxss
.notice{
width:100%;
height:68rpx;
background:rgba(255,255,255,1);
opacity:1;
margin-top: 20rpx;
margin-bottom: 20rpx;
display: flex;
justify-content:flex-start;
align-items:center;
padding-left: 20rpx;
padding-right: 20rpx;
box-sizing: border-box;
}
.notice .left{
width: 128rpx;
height: 44rpx;
background:linear-gradient(180deg,rgba(225,44,44,1) 0%,rgba(175,19,19,1) 100%);
transform:skewX(-15deg);
border-radius: 8rpx;
padding-left: 16rpx;
padding-right: 16rpx;
position: relative;
top: 0;
left: 0;
}
.notice .left view{
width: 96rpx;
position: absolute;
top: 46%;
left: 50%;
transform: translateX(-50%) translateY(-50%) skewX(15deg);
font-size:24rpx;
color: #fff;
white-space: nowrap;
}
.notice .right{
position: relative;
top: 0;
left: 0;
height:34rpx;
font-size:24rpx;
line-height:34rpx;
color:rgba(51,51,51,1);
margin-left: 10rpx;
overflow: hidden;
}
.scrollx{
width: 100%;
white-space: nowrap;
}
.notice-text-box{
position: absolute;
top: 0;
left: 0;
height: 34rpx;
display: flex;
justify-content: flex-start;
align-items: center;
}
.animte-move{
animation: move var(--time--) linear infinite;
}
@keyframes move{
0%{
transform: translateX(0);
}
100%{
transform: translateX(var(--width--));// var(--width--)使用传入的变量
}
}
.notice-text text{
padding-left: 10rpx;
padding-right: 10rpx;
}
js
data(){
width: 0,
ismove:false,
time:0,
}
const query = wx.createSelectorQuery();
query.select('.notice-text').boundingClientRect().exec((res) => {
that.setData({
width: res[0].width, //动态获取通知公告的宽度
ismove: true,
time:((that.data.width/375)*7).toFixed(2)+'s' //设置通知公告滚动的完需要的时间
})
// console.log(res[0].width)
// console.log(that.data.ismove)
});