如何实现文本动画中第二个文本的背景透明以适配视频背景?
问题与解决方案
问题
需要制作排版动画:第二个彩色文本包含多段内容,实现文本依次显示、隐藏的光标移动效果;但当前代码中用于实现擦除效果的伪元素背景色会遮挡背景视频,必须让span元素背景透明。
修改思路
原代码通过伪元素的实色背景覆盖文本实现擦除效果,这会遮挡背景视频。我们需要:
- 移除伪元素的背景色,仅保留光标样式
- 改用JavaScript实现逐字输入/删除的动画逻辑,避免依赖实色背景覆盖
修改后的完整代码
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="textAnim.css"> <title>Typography Animation</title> </head> <body> <!-- 背景视频示例 --> <video autoplay muted loop class="bg-video"> <source src="your-video-path.mp4" type="video/mp4"> </video> <div class="container"> <span class="text first-text">Absolute</span> <span class="text sec-text"></span> </div> </body> </html>
CSS
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600&display=swap'); *{ margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body{ min-height: 100vh; display: flex; align-items: center; justify-content: center; overflow: hidden; position: relative; } /* 背景视频样式 */ .bg-video{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; z-index: -1; } .container{ width: 360px; overflow: hidden; } .container .text{ position: relative; color: #c32000; font-size: 30px; font-weight: 600; } .container .text.first-text{ color: #FFF; } /* 仅保留光标样式,移除背景色 */ .text.sec-text:after{ content: ""; position: absolute; top: 0; right: -8px; height: 100%; width: 2px; background-color: #c32000; animation: blink 0.8s infinite; } /* 光标闪烁动画 */ @keyframes blink{ 0%, 100%{ opacity: 1; } 50%{ opacity: 0; } }
JavaScript
const textEl = document.querySelector(".sec-text"); const texts = ["Real Estate", "The Best Deal"]; let currentTextIndex = 0; let currentCharIndex = 0; let isDeleting = false; function typeText() { const currentText = texts[currentTextIndex]; if (!isDeleting) { // 逐字输入 textEl.textContent = currentText.substring(0, currentCharIndex + 1); currentCharIndex++; if (currentCharIndex === currentText.length) { // 输入完成后停顿 setTimeout(() => isDeleting = true, 2000); } } else { // 逐字删除 textEl.textContent = currentText.substring(0, currentCharIndex - 1); currentCharIndex--; if (currentCharIndex === 0) { // 删除完成后切换文本 isDeleting = false; currentTextIndex = (currentTextIndex + 1) % texts.length; } } // 控制输入/删除速度 const speed = isDeleting ? 150 : 200; setTimeout(typeText, speed); } // 启动动画 typeText();
关键修改说明
- 移除了伪元素的
background-color,将其改为右侧的闪烁光标,避免遮挡背景视频 - 用JavaScript实现逐字输入和删除的逻辑,替代原有的直接文本替换+背景覆盖的方式
- 添加了背景视频的示例代码,确保动画在视频背景上正常显示,无遮挡
内容的提问来源于stack exchange,提问作者shivani srivastav
相关产品推荐
相关产品推荐

