上一篇
html文字垂直轮播
- 行业动态
- 2025-04-30
- 2
使用CSS动画或JS定时器控制文字容器垂直位移,配合overflow隐藏实现 文字
实现原理
通过CSS动画或JavaScript控制文字元素的垂直位移,模拟向上滚动的效果,核心思路是让文字内容在容器内不断切换位置,形成循环轮播。
基础HTML结构
<div class="vertical-carousel"> <ul> <li>第一行文字</li> <li>第二行文字</li> <li>第三行文字</li> <li>第四行文字</li> </ul> </div>
CSS样式(纯CSS实现)
属性 | 说明 |
---|---|
height | 设置容器固定高度,仅显示一行文字 |
overflow: hidden | 隐藏超出容器的内容 |
animation | 定义垂直滚动的动画效果 |
.vertical-carousel { height: 30px; / 单行文字高度 / overflow: hidden; position: relative; } .vertical-carousel ul { position: absolute; top: 0; animation: scrollUp 5s linear infinite; / 每5秒循环一次 / } .vertical-carousel li { height: 30px; / 与容器高度一致 / } @keyframes scrollUp { 0% { top: 0; } 25% { top: -30px; } / 单行高度负值 / 50% { top: -60px; } 75% { top: -90px; } 100% { top: 0; } }
JavaScript增强版(支持暂停/恢复)
const carousel = document.querySelector('.vertical-carousel'); let isPaused = false; // 初始化动画 function startAnimation() { const ul = carousel.querySelector('ul'); ul.style.transition = 'top 0.5s'; // 添加过渡效果 ul.style.top = '0'; setInterval(() => { if (!isPaused) { const items = carousel.querySelectorAll('li'); let currentTop = parseInt(ul.style.top) || 0; const itemHeight = items[0].offsetHeight; ul.style.top = `${currentTop itemHeight}px`; // 向上移动 // 重置到顶部 if (currentTop <= -itemHeight (items.length 1)) { ul.style.top = '0'; } } }, 2000); // 每2秒移动一行 } // 暂停/恢复功能 carousel.addEventListener('mouseenter', () => { isPaused = true; }); carousel.addEventListener('mouseleave', () => { isPaused = false; }); startAnimation();
完整代码示例(带暂停效果)
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8">垂直文字轮播</title> <style> .vertical-carousel { height: 30px; overflow: hidden; border: 1px solid #ccc; padding: 0; margin: 20px; position: relative; } .vertical-carousel ul { padding: 0; margin: 0; list-style: none; position: absolute; top: 0; } .vertical-carousel li { height: 30px; line-height: 30px; text-align: center; } </style> </head> <body> <div class="vertical-carousel" id="carousel"> <ul> <li>第一行文字</li> <li>第二行文字</li> <li>第三行文字</li> <li>第四行文字</li> </ul> </div> <script> const carousel = document.getElementById('carousel'); let isPaused = false; const ul = carousel.querySelector('ul'); const itemHeight = carousel.querySelector('li').offsetHeight; function move() { if (!isPaused) { let currentTop = parseInt(ul.style.top) || 0; ul.style.top = `${currentTop itemHeight}px`; // 重置到顶部 if (currentTop <= -itemHeight 4) { // 4为li数量 ul.style.top = '0'; } } } setInterval(move, 2000); // 每2秒移动一行 carousel.addEventListener('mouseenter', () => { isPaused = true; }); carousel.addEventListener('mouseleave', () => { isPaused = false; }); </script> </body> </html>
常见问题与解答
问题1:如何调整滚动速度?
解答:修改JavaScript中的setInterval
时间参数(如改为1000
毫秒加速),或调整CSS动画的duration
值(如animation: scrollUp 3s linear infinite
)。
问题2:文字长度不一致导致错位怎么办?
解答:为li
设置固定宽度和text-align: center
,或使用Flex布局对齐文本。
.vertical-carousel li { display: flex; justify-content: center; }