小程序 实现chatgpt打字机效果
// pages/index/index.js
Page({
data: {
textToDisplay: '', // 要显示的文字
typingSpeed: 100, // 打字速度,单位:毫秒
},
// 生命周期函数--监听页面加载
onLoad: function () {
// 获取要显示的文字
const originalText = "你好,这是一个打字机效果的示例。";
// 调用打字机效果函数
this.typewriterEffect(originalText);
},
// 打字机效果函数
typewriterEffect(text) {
let currentIndex = 0;
const { typingSpeed } = this.data;
const typingInterval = setInterval(() => {
const partialText = text.slice(0, currentIndex + 1);
this.setData({
textToDisplay: partialText,
});
currentIndex++;
// 判断是否已经显示完所有文字
if (currentIndex === text.length) {
clearInterval(typingInterval); // 清除定时器
}
}, typingSpeed);
},
});
在上面的代码中,我们使用setInterval来定时更新要显示的文字,从而实现打字机效果。通过逐步增加currentIndex,我们可以逐渐显示完整的文本。在小程序的WXML文件中,你可以通过绑定textToDisplay来显示文字。
请注意,你可以根据需要调整typingSpeed来控制打字速度。这只是一个简单的实现方式,你可以根据实际需求进行更复杂的定时器控制或使用其他动画效果库。