Skip to main content

typed.js

基础使用

安装

yarn add typed.js

创建实例

通过字符串

new Typed('#demo', {
strings: ["Hello World", "Typed.js 示例"],
typeSpeed: 100,
backSpeed: 50,
startDelay: 1000
});

HTML + CSS

<!-- 核心代码 -->
<span id="target" style="white-space: pre-wrap;line-height: 30px;"></span>

<!-- 在span标签内加入 white-space: pre-wrap 样式,在strings内的语句中加入\n换行符可以实现换行 -->
<script src="https://cdn.bootcss.com/typed.js/2.0.9/typed.min.js"></script>
<script type="text/javascript">
const options = {
strings: [
'First test.',
'Second test, \nit will pause for three seconds. ^3000',
"Second test, \nthe last sentence will go back to 'Second test, ', \noh no, this is the third test. ^1000",
"It's going to start repeating."
],
typeSpeed: 50, //打印速度
startDelay: 300, //开始之前的延迟300毫秒
loop: true, //是否循环
};
const typed = new Typed('#target', options);
</script>

React

import Typed from "typed.js";
import { useEffect, useRef } from "react";
const TypedTitle = () => {
const el = useRef(null);
useEffect(() => {
const typed = new Typed(el.current, {
strings: [
"Full stack developer",
"Front-end developer",
"React Developer",
],
startDelay: 300,
typeSpeed: 100,
backSpeed: 100,
backDelay: 100,
loop: true,
});

// Destroying
return () => {
typed.destroy();
};
}, []);
return (
<h1>
I am <span ref={el}></span>{" "}
</h1>
);
};

字段类型说明
stringsnumber类型速度,类型速度,以毫秒为单位
startDelay
typeSpeed
backSpeed
backDelay
loop
smartBackspace
stringsElement

基础配置 - Options

字段类型默认值说明
stringsArray[]必需,要显示的字符串数组
stringsElementStringnull从 DOM 元素获取字符串(如 #myElement
typeSpeedNumber40打字速度(单位:毫秒)
startDelayNumber0开始打字前的延迟时间
backSpeedNumber0退格速度(设为 0 表示禁用退格)
backDelay
smartBackspaceBooleantrue仅删除与前一个字符串不同的部分