css制作弹幕
使用CSS制作弹幕效果
弹幕效果可以通过CSS动画和HTML结合实现。以下是两种常见的实现方式:
方式一:使用CSS动画控制水平移动
<div class="danmu-container">
<div class="danmu">这是一条弹幕</div>
</div>
.danmu-container {
position: relative;
width: 100%;
height: 100px;
overflow: hidden;
border: 1px solid #ccc;
}
.danmu {
position: absolute;
white-space: nowrap;
color: white;
background-color: rgba(0,0,0,0.5);
padding: 5px 10px;
border-radius: 15px;
animation: move 5s linear infinite;
}
@keyframes move {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
方式二:多行弹幕效果
<div class="danmu-stage">
<span class="bullet">弹幕1</span>
<span class="bullet">弹幕2</span>
<span class="bullet">弹幕3</span>
</div>
.danmu-stage {
position: relative;
height: 300px;
overflow: hidden;
background-color: #000;
}
.bullet {
position: absolute;
color: #fff;
font-size: 16px;
white-space: nowrap;
animation: fly 8s linear;
animation-fill-mode: forwards;
}
@keyframes fly {
0% {
transform: translateX(100%);
top: 10%;
}
100% {
transform: translateX(-100%);
top: 10%;
}
}
.bullet:nth-child(2) {
animation-delay: 1s;
top: 30%;
}
.bullet:nth-child(3) {
animation-delay: 2s;
top: 50%;
}
实现弹幕的进阶技巧
随机位置和颜色
/* 添加随机样式 */
.bullet {
/* 其他样式 */
color: hsl(calc(360 * var(--rand)), 100%, 70%);
top: calc(var(--rand) * 80%);
}
/* 通过JavaScript设置随机变量 */
document.querySelectorAll('.bullet').forEach(el => {
el.style.setProperty('--rand', Math.random());
});
弹幕速度和方向控制
@keyframes fly {
0% {
transform: translateX(calc(100% + 20px));
}
100% {
transform: translateX(calc(-100% - 20px));
}
}
/* 不同速度 */
.bullet.fast {
animation-duration: 4s;
}
.bullet.slow {
animation-duration: 12s;
}
弹幕交互功能
暂停和播放控制
.danmu-container:hover .danmu {
animation-play-state: paused;
}
弹幕碰撞检测(需要JavaScript配合)
function checkCollision() {
const bullets = document.querySelectorAll('.bullet');
bullets.forEach(bullet => {
// 检测碰撞逻辑
});
requestAnimationFrame(checkCollision);
}
checkCollision();
这些方法可以组合使用,创建出各种复杂的弹幕效果。实际应用中,通常会结合JavaScript动态生成弹幕内容和控制动画参数。







