# 极客风打字效果

  1. html部分

预览链接 (opens new window)

<main>
    <h1>
      <span id="text" data-text='["我是小明","我是前端工程师","我热爱前端开发"]'></span>
      <span class="mark"></span>
    </h1>
  </main>
1
2
3
4
5
6
  1. css部分
* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
	font-family: 'webfont', 'PingFang FC', 'Microsoft Yahei', sans-serif;
}
@font-face {
	font-family: 'webfont';
	font-display: swap;
	src: url('http://at.alicdn.com/t/webfont_zxrpok1zwxn.eot'); /* IE9*/
	src: url('http://at.alicdn.com/t/webfont_zxrpok1zwxn.eot?#iefix')
			format('embedded-opentype'),
		/* IE6-IE8 */ url('http://at.alicdn.com/t/webfont_zxrpok1zwxn.woff2')
			format('woff2'),
		url('http://at.alicdn.com/t/webfont_zxrpok1zwxn.woff') format('woff'),
		/* chrome、firefox */ url('http://at.alicdn.com/t/webfont_zxrpok1zwxn.ttf')
			format('truetype'),
		/* chrome、firefox、opera、Safari, Android, iOS 4.2+*/
			url('http://at.alicdn.com/t/webfont_zxrpok1zwxn.svg#杨任东竹石体-Bold')
			format('svg'); /* iOS 4.1- */
}
main {
	display: flex;
	background-color: #2f3542;
	justify-content: center;
	align-items: center;
	height: 100vh;
}
h1 {
	color: #fff;
	font-size: 5em;
	font-weight: 300;
}
span.mark {
	border-right: solid 2px #fff;
	animation: blink 0.5s step-end infinite;
	/* animation: blink 0.5s steps(40, end) infinite; */
}
@keyframes blink {
	from,
	to {
		border-color: transparent;
	}

	50% {
		border-color: #fff;
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  1. js部分
/*
 * @Author: your name
 * @Date: 2021-05-14 18:12:55
 * @LastEditTime: 2021-05-14 19:28:27
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /常规js操作/css项目/极客风打字/index.js
 */

const textEl = document.querySelector('#text');
const texts = JSON.parse(textEl.getAttribute('data-text'));

let index = 0;
let charIndex = 0;
let delta = 500;

let start = null;
let isDeleting = false;

function type(time) {
	// console.log(time, '==time');
	window.requestAnimationFrame(type);
	if (!start) start = time;
	let progress = time - start;

	if (progress > delta) {
		let text = texts[index];
		if (!isDeleting) {
			textEl.innerHTML = text.slice(0, ++charIndex);
			delta = 500 - Math.random() * 400;
		} else {
			textEl.innerHTML = text.slice(0, charIndex--);
		}
		start = time;
		if (charIndex == text.length) {
			isDeleting = true;
			delta = 200;
			start = time + 1200;
		}

		if (charIndex < 0) {
			isDeleting = false;
			start = time + 200;
			index = ++index % texts.length;
		}
	}
}

window.requestAnimationFrame(type);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
最后更新时间: 5/15/2023, 6:25:18 PM