<p>CSS实现打字机动画效果,核心在于巧妙利用steps()
overflow: hidden
white-space: nowrap
<span>
<p>
<p>CSS怎样实现打字机动画效果?steps()函数详解<p><span>立即学习“前端免费学习笔记(深入)”;
.typewriter p {
font-family: 'Mono', monospace; /* 选用等宽字体,效果更佳 */
overflow: hidden; /* 隐藏超出容器的内容 */
white-space: nowrap; /* 文本不换行 */
border-right: .15em solid orange; /* 模拟光标 */
width: 0; /* 初始宽度为0 */
animation:
typing 4s steps(30, end) forwards, /* 打字动画,30是字符数 */
blink-caret .75s step-end infinite; /* 光标闪烁动画 */
}
/* 打字动画 */
@keyframes typing {
from { width: 0 }
to { width: 100% } /* 宽度从0到100% */
}
/* 光标闪烁动画 */
@keyframes blink-caret {
from, to { border-color: transparent }
50% { border-color: orange; }
}overflow: hidden;
white-space: nowrap;
width: 0;
border-right: .15em solid orange;
animation: typing 4s steps(30, end) forwards, blink-caret .75s step-end infinite;
typing 4s steps(30, end) forwards
4s
steps(30, end)
30
end
forwards
blink-caret .75s step-end infinite
step-end
width
border-right
border-right: .15em solid orange;
blink-caret
@keyframes
@keyframes blink-caret {
from, to { border-color: transparent } /* 动画开始和结束时,边框颜色透明 */
50% { border-color: orange; } /* 动画进行到一半时,边框颜色变为可见 */
}animation: blink-caret .75s step-end infinite;
step-end
from, to { border-color: transparent }50% { border-color: orange; }infinite
steps()
steps()
background-position
.sprite-animation {
width: 100px;
height: 100px;
background-image: url('walk-sprite.png');
background-position: 0 0; /* 初始位置 */
animation: walk 1s steps(8) infinite; /* 8帧,每秒一循环 */
}
@keyframes walk {
to { background-position: -800px 0; } /* 8帧 * 100px = 800px */
}background-position
steps()
steps()
setTimeout
Promise
<span>
<p>
steps()
animationend
// 伪代码示例
const texts = [
"这是第一段文字,会先打出来。",
"然后是第二段,稍微长一点,模拟思考。",
"最后是第三段,结束语。"
];
let textIndex = 0;
function typeText(text) {
const container = document.querySelector('.typewriter');
const p = document.createElement('p');
p.textContent = text;
container.appendChild(p);
// 计算字符数
const charCount = text.length;
// 动态设置CSS变量,或者直接设置style属性
p.style.setProperty('--char-count', charCount);
p.style.animation = `typing ${charCount * 0.1}s steps(var(--char-count), end) forwards, blink-caret .75s step-end infinite`;
p.addEventListener('animationend', () => {
// 动画结束后,移除光标闪烁动画(可选)
p.style.animation = `typing ${charCount * 0.1}s steps(var(--char-count), end) forwards`;
// 或者直接隐藏光标:p.style.borderRight = 'none';
textIndex++;
if (textIndex < texts.length) {
setTimeout(() => typeText(texts[textIndex]), 1000); // 1秒后开始下一段
}
}, { once: true }); // 确保事件只触发一次
}
// 初始调用
typeText(texts[textIndex]);animation-play-state
width
overflow
white-space
以上就是CSS怎样实现打字机动画效果?steps()函数详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号