简单实现打字效果


本来想写个小玩意儿,正好需要用到打字效果,稍微研究了下。

直接看完成后的效果

实现思路其实就是:利用定时器然后从段落中每次获取一个字,下标依次递增,组成新的字符串

我这里倒是在用小程序写这个功能,所以直接写小程序的语法了。

wxml

1
2
3
4
<view class="mes-wrap" wx:if="{{isShowPraise}}">
<image class="image-animation" src="../../images/4.jpg" mode="aspectFill" animation="{{animationData}}"></image>
{{successMes}}
<view>

js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
data: {
words: "古巴比伦王颁布了\n汉摩拉比法典\n刻在黑色的玄武岩\n距今已经三千七百多年", // 段落
successMes: "", // 渲染的段落
wordIndex: 0, // 记录下标
},
handleShowWord() {
const { wordIndex, words } = this.data;
if (wordIndex <= words.length) {
const _index = wordIndex + 1
const word = `${words.slice(0, _index)}_`;
this.setData({
wordIndex: _index,
successMes: word
})
setTimeout(() => {
this.handleShowWord();
}, 100)
} else {
const _ = words.slice(0, words.length);
this.setData({
successMes: _
})
}
}

wxss

1
2
3
4
.mes-wrap {
white-space: pre-wrap; // 支持换行符换行
line-height: 40px;
}

函数执行的时候,定时器开启,根据记录的下标,去判断是否继续往下取字,唯一需要注意的是换行的问题,在字符串中我们添加了\n换行符之后,要写css让浏览器保留空白符,并且可以正常换行。

我的微信公众号: 梨的前端小屋


文章作者: 梨啊梨
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 梨啊梨 !
  目录