wxml部分:
<view class="notice">
<image src="../../static/horn.png" mode="widthFix"></image>
<view class="notice_desc">
<view style="transform: translateX(-{{ distance }}px);">
<text style="margin-right:{{ space }}px;"></text>
<text id="mjltest">{{ text }}</text>
<text style="margin-right:{{ space }}px;"></text>
<text>{{ text }}</text>
</view>
</view>
</view>
wxss部分:
.notice {
width: 92%;
height: 56rpx;
line-height: 56rpx;
background-color: #fff;
box-shadow: 0 3rpx 6rpx 1rpx rgba(0,97,6,0.4100);
border-radius: 30rpx;
position: absolute;
top: 730rpx;
left: 30rpx;
display: flex;
}
.notice image {
width: 36%;
margin: 10rpx 18rpx;
}
.notice .notice_desc {
margin-right: 40rpx;
font-size: 28rpx;
color: #333;
overflow: hidden;
white-space: nowrap;
}
js部分:
Page({
data: {
text: "需要滚动的字幕",
step: 1, // 滚动速度
distance: 360, // 初始滚动距离
space: 300,
interval: 20 // 时间间隔
},
onShow: function() {
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; // 屏幕宽度
var 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);
}
})