简介
Typed.js 是一个轻量级的 JavaScript 库,用于创建打字机效果。它可以让文本以打字机的方式逐字显示,支持多种配置选项和动画效果。
主要特性
- 简单易用: 只需几行代码即可实现打字机效果
- 高度可配置: 支持速度控制、循环播放、暂停等功能
- 多种动画: 支持删除、暂停、循环等动画模式
- 无依赖: 纯 JavaScript 实现,无需其他依赖库
- 响应式: 支持移动端和桌面端
安装
npm install typed.js
# OR
yarn install typed.js
参数
—- 参数名 — | — 类型 — | — 默认值 — | — 描述 — |
---|---|---|---|
strings | Array | [] | 要显示的字符串数组 |
stringsElement | String、Element | null | 包含字符串的 HTML 元素的 ID |
typeSpeed | Number | 0 | 打字速度(每秒字符数) |
startDelay | Number | 0 | 开始打字前的延迟时间(毫秒) |
backSpeed | Number | 0 | 删除字符的速度(每秒字符数) |
smartBackspace | Boolean | false | 是否智能删除字符 |
shuffle | Boolean | false | 是否随机打乱字符串 |
backDelay | Number | 700 | 删除字符后的延迟时间(毫秒) |
fadeOut | Boolean | false | 是否淡出效果 |
fadeOutClass | String | 淡出效果的 CSS 类名 | |
fadeOutDelay | Number | 500 | 淡出效果的延迟时间(毫秒) |
loop | Boolean | false | 是否循环播放 |
loopCount | Number | Infinity | 循环播放次数 |
showCursor | Boolean | true | 是否显示光标 |
cursorChar | String | 光标字符 | |
autoInsertCss | Boolean | true | 是否自动插入 CSS 样式 |
attr | String | ‘placeholder’ | 要打字的属性名 |
bindInputFocus | Boolean | false | 是否绑定输入框焦点事件 |
contentType | String | ‘html’ | 内容类型(’html’ 或 ‘null’) |
事件
事件名 | 描述 |
---|---|
onBegin | 打字机开始时触发(只触发一次) |
onComplete | 打字机完成打字时触发 |
preStringTyped | 打字前触发 |
onStringTyped | 打字后触发 |
onLastStringBackspaced | 最后一个字符串删除时触发 |
onTypingPaused | 打字暂停时触发 |
onTypingResumed | 打字恢复时触发 |
onReset | 打字机重置时触发 |
onStop | 打字机停止时触发 |
onStart | 打字机动画开始时触发(loop: true, 会触发多次) |
onDestroy | 打字机销毁时触发 |
使用示例
基础使用

import React from "react";
import Typed from "typed.js";
function TypedComponent() {
const el = React.useRef(null);
React.useEffect(() => {
const typed = new Typed(el.current, {
strings: ["Hello Typed.js", "https://code.ifrontend.net", "腾辉源码分享"],
typeSpeed: 50,
cursorChar: "_",
loop: true,
showCursor: false,
});
return () => {
typed.destroy();
};
}, []);
return (
<div className="container p-10">
<span ref={el} className="text-xl font-bold text-gray-800" />
</div>
);
}
export default TypedComponent;
Input 使用

import React from "react";
import Typed from "typed.js";
function MyComponent() {
const el = React.useRef(null);
React.useEffect(() => {
const typed = new Typed(el.current, {
strings: ["Hello Typed.js", "https://code.ifrontend.net", "腾辉源码分享"],
typeSpeed: 50,
cursorChar: "_",
loop: true,
showCursor: false,
});
return () => {
typed.destroy();
};
}, []);
return (
<div className="container p-10">
<input
ref={el}
placeholder="请输入"
className="border-2 border-gray-300 rounded-md p-2"
/>
</div>
);
}
export default MyComponent;
颜色设置
React.useEffect(() => {
const typed = new Typed(el.current, {
strings: [
"Hello Typed.js",
"<span class='text-red-500'>https://code.ifrontend.net</span>",
"<span class='text-blue-500'>腾辉源码分享</span>",
],
typeSpeed: 50,
cursorChar: "_",
backSpeed: 0,
loop: true,
});
return () => {
typed.destroy();
};
}, []);
原文链接:https://code.ifrontend.net/archives/620,转载请注明出处。
评论0