css制作弹幕
使用 CSS 制作弹幕效果
弹幕效果可以通过 CSS 动画和 HTML 结构实现。以下是实现弹幕效果的具体方法:
创建 HTML 结构
<div class="danmu-container">
<div class="danmu">这是一条弹幕</div>
<div class="danmu">另一条弹幕</div>
</div>
基础 CSS 样式
.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
background-color: #000;
}
.danmu {
position: absolute;
color: white;
font-size: 16px;
white-space: nowrap;
}
添加动画效果
@keyframes moveRight {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
.danmu {
animation: moveRight 10s linear infinite;
}
随机位置和延迟
.danmu:nth-child(1) {
top: 10%;
animation-delay: 0s;
}
.danmu:nth-child(2) {
top: 30%;
animation-delay: 2s;
}
高级优化
-
使用 JavaScript 动态添加弹幕

function addDanmu(text) { const danmu = document.createElement('div'); danmu.className = 'danmu'; danmu.textContent = text; danmu.style.top = Math.random() * 100 + '%'; danmu.style.animationDuration = (Math.random() * 5 + 5) + 's'; document.querySelector('.danmu-container').appendChild(danmu); } -
弹幕颜色和样式

.danmu { text-shadow: 1px 1px 2px #000; padding: 2px 10px; border-radius: 10px; background-color: rgba(0, 0, 0, 0.5); } -
多方向弹幕
@keyframes moveLeft { from { transform: translateX(-100%); } to { transform: translateX(100%); } }
.danmu.reverse { animation-name: moveLeft; }
#### 性能优化
- 使用 `will-change: transform` 提升动画性能
- 限制同时显示的弹幕数量
- 移除屏幕外的弹幕元素
#### 浏览器兼容性
- 现代浏览器都支持 CSS 动画
- 对于旧版浏览器,可以添加 `-webkit-` 前缀
- 考虑使用 requestAnimationFrame 作为降级方案






