先呈上效果图
滚动速度可调节,右侧关闭按钮可关闭。
主要代码
//wxml部分
<view class="scroll-top" hidden="{{isHiddenMsg}}">
<scroll-view>
<view class="msg-icon notice-icon">
<image src="../../../static/images/show-info/msg.png"></image>
</view>
<view class="scrollbar" style="transform: translateX(-{{distance}}px)">
<text style="margin-right:{{space}}px;"></text>
<text id="mjltest">{{announcementText}}</text>
<text style="margin-right:{{space}}px;"></text>
<text>{{announcementText}}</text>
</view>
<view class="msg-icon close-icon" catchtap="closeMsg">
<image src="../../../static/images/show-info/close.png"></image>
</view>
</scroll-view>
</view>
//wxss部分
/* 文字滚动 */
.scroll-top{
background-color: #fffbd6;
position: fixed;
z-index: 2;
}
.msg-icon{
display: inline-block;
width: 70rpx;
background-color: #fffbd6;
z-index: 2;
text-align: center;
}
.notice-icon{
position: absolute;
left: 0;
top: 16rpx;
}
.close-icon{
position: absolute;
left: 680rpx;
top:16rpx;
padding-right: 16rpx;
}
.msg-icon>image{
width: 48rpx;
height: 48rpx;
}
.weui-label,.weui-input,.weui-select,.check-info-btn{
font-size: 30rpx;
}
.scrollbar{
color: #e0620d;
white-space: nowrap;
font-size: 14px;
height: 80rpx;
line-height: 80rpx;
}
//js部分
var interval;
data: {
isHiddenMsg: false,
announcementText: "在三证合一期间,企业税号大量变更,请自行核实开票信息,避免废票!",
//滚动速度
step: 1,
//初始滚动距离
distance: 0,
space: 30,
// 时间间隔
interval: 20,
}
onLoad(){
this.topScroll();
},
/** 关闭顶部通知 */
closeMsg(){
this.setData({ isHiddenMsg: true});
clearInterval(interval);
},
/** 获取滚动条基本信息 */
topScroll(){
var that = this;
var query = wx.createSelectorQuery();
//选择id
query.select('#mjltest').boundingClientRect()
query.exec(function (res) {
var length = res[0].width;
var windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕宽度
that.setData({
length: length,
windowWidth: windowWidth,
space: windowWidth
});
that.scrollling(); // 第一个字消失后立即从右边出现
});
},
/** 向左滚动 */
scrollling: function () {
var that = this;
var length = that.data.length; //滚动文字的宽度
var windowWidth = that.data.windowWidth; //屏幕宽度
let interval = setInterval(function () {
var maxscrollwidth = length + that.data.space;
var left = that.data.distance;
if (left < maxscrollwidth) { //判断是否滚动到最大宽度
that.setData({
distance: left + that.data.step
})
} else {
that.setData({
distance: 0 // 直接重新滚动
});
clearInterval(interval);
that.scrollling();
}
}, that.data.interval);
},
如果您有更好的思路,欢迎分享和交流。
注:本文是从另一个博主稍加修改,原文地址忘记了,在此 就不注明了