我在小程序中實現的這種效果:javascript
模板中代碼以下:java
<!--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文件以下:express
//動態打印輸出文字的方法
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()方法。小程序