代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>全屏弹幕</title>
<style>
/* 页面主体样式,确保无边距、无内边距、无滚动条,高度为100%,背景色为黑色 */
body, html {
margin: 0;
padding: 0;
overflow: hidden;
height: 100%;
background-color: black;
}
/* 弹幕容器样式,绝对定位,覆盖整个页面,不允许鼠标事件 */
.danmu-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
/* 单条弹幕样式,绝对定位,内容不换行,白色字体,24px大小,加粗 */
.danmu {
position: absolute;
white-space: nowrap;
color: white;
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<!-- 弹幕容器元素 -->
<div class="danmu-container" id="danmuContainer"></div>
<script>
// 获取弹幕容器元素
const danmuContainer = document.getElementById('danmuContainer');
/**
* 创建并添加一条弹幕
* @param {string} text 弹幕文本内容
*/
function createDanmu(text) {
const danmu = document.createElement('div');
danmu.className = 'danmu';
danmu.textContent = text;
// 设置弹幕的位置和初始位置
const startTop = Math.random() * (window.innerHeight - 30); // 防止弹幕超出窗口
danmu.style.top = `${startTop}px`;
danmu.style.left = `${window.innerWidth}px`;
danmuContainer.appendChild(danmu);
// 设置弹幕的移动时间
const duration = 10 + Math.random() * 10; // 弹幕移动时间 10-20 秒
// 动画效果:从右向左移动到视图外
danmu.animate([
{ transform: `translateX(-${window.innerWidth + danmu.clientWidth}px)` }
], {
duration: duration * 1000,
easing: 'linear',
iterations: 1,
fill: 'forwards'
}).onfinish = () => {
danmuContainer.removeChild(danmu);
};
}
/**
* 开始发送弹幕
*/
function startDanmu() {
// 每隔1秒添加一条弹幕
setInterval(() => createDanmu('Ciallo~(∠・ω< )⌒★'), 1000);
}
// 启动弹幕
startDanmu();
</script>
</body>
</html>
预览
看这里或者这儿

