我在小程序中实现的这种效果:
模板中代码如下:
<!--index.wxml-->
<view class='user'>
<view class="userinfo">
<button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
<block wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
<!--motto就是要动态输出的内容--->
<textarea disabled style="font-size:18px;width:70%;color:{{fontColor}}" value='{{motto}}'></textarea>
</view>
js文件如下:
//动态打印输出文字的方法
print:function(words,inx) {
this.setData({ motto: words.substring(0, inx++),index:inx})
if(words.length<inx) {
clearInterval(this.data.timeId)
}
// console.log(inx)
},
onLoad: function () {
var that = this
var words = 'CSDN地址:https://blog.csdn.net/Lee_woxinyiran \n简书地址:https://www.jianshu.com/u/b0bdd6db3cc8 \n\n欢迎访问o(* ̄︶ ̄*)o'
var color = ['#000', '#2f3192', '#c00', '#a286bd', '#9900cc']
var id =setInterval(function () {
var inx = that.data.index
that.print(words, inx)
var idx = Math.ceil(Math.random() * 4 + 0)
that.setData({fontColor:color[idx]})
}, 100)
}
其实我是在onLoad先定义好要输出的内容,字体颜色。然后使用定时器去调用print()打印输出这个方法。在print()方法中,根据传入的参数,动态的截取内容并输出,并判断当前输出字符的位置是否大于总长度,大于的话,就停止定时器,不然会一直调用print()方法。