近期有一个显示文字水平滚动的需求,思考了半天写了几行小程序代码,一言不合就上代码:
wxml
<view class="rollCon">
<view class="box">
<view class="text" style="left:{{offsetLeft}}px"> {{text}} </view>
</view>
</view>
wxss
.rollCon{position: fixed;bottom: 0;left: 0;width: 100%;height: 60rpx;z-index: 100;background: #FDE8C7;font-size: 20rpx;line-height: 60rpx;}
.box {width: 100%;position: relative;}
.text {white-space: nowrap;position: absolute;top: 0;}//注意一定要用nowrap。。。
js
data={text:'共0张 价税合计:12121 金额:2323233 税额:232423',
pace: 1,//滚动速度
start: 0,//初始滚动距离
interval:20,//时间间隔
size:14,
length:0,
windowWidth:0,}
//文字走马灯
run(){
let that = this;
let interval = setInterval(function () {if (-that.start < that.length) {
that.start = that.start - that.pace;
that.$apply();
} else {
clearInterval(interval);
that.start = that.windowWidth;
that.run();
that.$apply();}
}, that.interval);}
onshow(){
//文字滚动
let length = (this.text.length-20) * this.size;//文字长度
let windowWidth = wx.getSystemInfoSync().windowWidth;// 屏幕宽度
this.length = length;this.windowWidth = windowWidth;
this.$apply()
this.run();}
定时器每次触发时,调用this.$apply()来更新data数据 ,要不每次只执行一次,数据 得不到改变!!!