首页滚动字幕实现与调整
度娘查到滚动字幕样式如下
试用后发现开发者工具导致电脑CPU达到90%居高不下,然后工具卡顿不动的情况。换了开发者工具版本还是卡顿无响应,定位问题发现是刚刚加在首页的滚动字幕引发问题。将 onShowScrollingTxt 方法不要放到 onShow 中,放到 onLoad 中调用就可以正常运行(小程序分为三个tab页面,字幕位于首个tab中,只需要加载一次即可)。代码如下
index.js
data: {
text: "疫情期间宅家做什么?邀约组局LOL开黑游戏,邀约组织一个云上会议,邀约好友一起直播互动 ... ",
marqueePace: 0.5,//滚动速度
marqueeDistance: 0,//初始滚动距离
marquee_margin: 0,
size: 28,
interval: 20 // 时间间隔
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.onShowScrollingTxt();
},
/**
* 滚动字幕
*/
onShowScrollingTxt: function () {
var that = this;
var length = that.data.text.length * that.data.size;//文字长度
var windowWidth = wx.getSystemInfoSync().windowWidth;// 屏幕宽度
that.setData({
length: length,
windowWidth: windowWidth
});
that.scrolltxt();// 第一个字消失后立即从右边出现
},
scrolltxt: function () {
var that = this;
var length = that.data.length;//滚动文字的宽度
var windowWidth = that.data.windowWidth;//屏幕宽度
if (length > windowWidth){
var interval = setInterval(function () {
var maxscrollwidth = length + that.data.marquee_margin;//滚动的最大宽度,文字宽度+间距,如果需要一行文字滚完后再显示第二行可以修改marquee_margin值等于windowWidth即可
var crentleft = that.data.marqueeDistance;
if (crentleft < maxscrollwidth) {//判断是否滚动到最大宽度
that.setData({
marqueeDistance: crentleft + that.data.marqueePace
})
}else {
//console.log("替换");
that.setData({
marqueeDistance: 0 // 直接重新滚动
});
clearInterval(interval);
that.scrolltxt();
}
}, that.data.interval);
}else{
that.setData({ marquee_margin:"1000"});//只显示一条不滚动右边间距加大,防止重复显示
}
},
index.wxml
<view style='-webkit-overflow-scrolling: touch'>
<view><image src="/images/scroll-info.jpg" class="scroll-info-speaker"/></view>
<view class='scroll-info'>
<scroll-view style='-webkit-overflow-scrolling: touch'>
<view class="scrolltxt clr_g">
<view class="marquee_box">
<view class="marquee_text" style="transform: translateX(-{{marqueeDistance}}px)">
<text class="clr_g">{{text}}</text>
<text style="margin-right:{{marquee_margin}}px;" class="clr_g"></text>
<text style="margin-right:{{marquee_margin}}px;" class="clr_g">{{text}}</text>
</view>
</view>
</view>
</scroll-view>
</view>
</view>
index.wxss
.scroll-info-speaker {
width: 30px;
height: 30px;
}
.scroll-info {
padding-left: 30px;
margin-top: -40px;
}
.scrolltxt{
padding:0 20rpx;
color:#78b3e4;
}
.marquee_box {
position:relative;
color:#78b3e4;
height:90rpx;
display:block;
overflow:hidden;
}
.marquee_text {
white-space: nowrap;
position:absolute;
top:0;
font-size:28rpx;
height:90rpx;
line-height:90rpx;
}