本文主要介紹了純html+css實(shí)現(xiàn)打字效果,具有一定的參考價(jià)值,感興趣的可以了解一下
效果圖

分析
可以將動(dòng)畫(huà)看做三個(gè)不同的層次:
- 最底層的文字
- 中間擋住文字的背景
- 最上層的光標(biāo)
文字是靜止的,而中間的背景和最上層的光標(biāo)是動(dòng)態(tài)的。
初始時(shí),背景擋住所有的文字,光標(biāo)在最左邊。
動(dòng)畫(huà)進(jìn)行時(shí),背景和光標(biāo)以相同的步伐從左往右移動(dòng)。
動(dòng)畫(huà)結(jié)束時(shí),背景不再遮擋文字,光標(biāo)則在最右邊閃爍。

代碼
html
<div class="text">hello,world!</div>
css
:root {
/* 字符數(shù)量 */
--steps: 12;
/* 動(dòng)畫(huà)時(shí)間 */
--duration: 2.5s;
/* 字體大小 */
--fontSize: 50px;
/* 光標(biāo)大小 */
--cursorSize: 20px;
}
.text {
color: #333;;
position: relative;
display: inline-block;
font-family: 'Courier New', Courier, monospace;
font-size: var(--fontSize);
line-height: 1;
}
.text::after {
content: '';
width: var(--cursorSize);
height: var(--fontSize);
background-color: black;
z-index: 2;
position: absolute;
animation: blink 1s var(--duration) step-end infinite,
moveCursor var(--duration) steps(var(--steps)) forwards;
}
.text::before {
content: '';
width: 100%;
height: var(--fontSize);
z-index: 1;
position: absolute;
background: linear-gradient(#fff, #fff) no-repeat top right;
animation: showText var(--duration) steps(var(--steps)) forwards;
}
/* 光標(biāo)閃爍動(dòng)畫(huà) */
@keyframes blink {
0% {
background-color: black;
}
50% {
background-color: transparent;
}
100% {
background-color: black;
}
}
/* 光標(biāo)移動(dòng)動(dòng)畫(huà) */
@keyframes moveCursor {
0% {
left: 0%;
}
100% {
left: 100%;
}
}
/* 背景移動(dòng)動(dòng)畫(huà) */
@keyframes showText {
0% {
background-size: 100% 100%;
}
100% {
background-size: 0% 100%;
}
}
注意
字體必須是等寬字體。因?yàn)楣鈽?biāo)每次移動(dòng)的距離是是根據(jù)字符的數(shù)量 / 總寬度來(lái)決定的。
在線演示
到此這篇關(guān)于純html+css實(shí)現(xiàn)打字效果的文章就介紹到這了,更多相關(guān)html css打字效果內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!