CSS实现文字逐字显示的核心是利用animation的steps()函数,将动画分割为离散步骤,使文本像打字机一样逐字出现。首先通过设置width:0和overflow:hidden隐藏文本,再用animation配合steps()函数逐步增加宽度,实现逐字显示效果。steps()函数接受两个参数:步数和起始时机(start或end),默认为end,表示在每步结束时更新样式。为提升性能,应避免触发重排的属性动画,可使用will-change或硬件加速优化渲染。响应式设计中,推荐使用相对单位(如vw、em)、媒体查询调整动画时长,或结合JavaScript动态计算文本长度与动画时间,确保不同屏幕下的良好表现。光标闪烁效果通过border-right与blink-caret动画实现,增强视觉反馈。<p>
<p>CSS实现文字逐字显示,核心在于利用animation
steps()
<p>
overflow: hidden
animation
steps()
<p class="typing-text">Hello, world! This is a typing effect.</p>
.typing-text {
width: 0;
overflow: hidden;
white-space: nowrap; /* 防止文本换行 */
border-right: .15em solid orange; /* 添加闪烁的光标 */
animation: typing 4s steps(40, end) forwards, /* 4s 是动画总时长, 40 是字符数 */
blink-caret .75s step-end infinite;
}
/* typing 动画 */
@keyframes typing {
from { width: 0 }
to { width: 100% }
}
/* 光标闪烁动画 */
@keyframes blink-caret {
from, to { border-color: transparent }
50% { border-color: orange; }
}steps(40, end)
end
forwards
step-end
steps()
steps()
animation-timing-function
start
end
start
end
end
steps(10, start)
end
end
width
will-change
requestAnimationFrame
requestAnimationFrame
requestAnimationFrame
transform: translateZ(0)
backface-visibility: hidden
em
rem
vw
resize
window.addEventListener('resize', function() {
// 重新计算文本宽度和动画时长
let textElement = document.querySelector('.typing-text');
let textLength = textElement.textContent.length;
let newWidth = textElement.offsetWidth; // 获取当前元素的宽度
let animationDuration = textLength * 0.1; // 假设每个字符需要0.1秒
textElement.style.animation = `typing ${animationDuration}s steps(${textLength}, end) forwards, blink-caret .75s step-end infinite`;
});以上就是CSS怎样制作文字逐字显示效果?animation steps分帧动画的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号