jquery 弹幕
jQuery 弹幕实现方法
使用 jQuery 实现弹幕功能可以通过动态创建元素并控制其动画效果来完成。以下是具体实现步骤:
HTML 结构
<div id="danmu-container" style="position: relative; width: 800px; height: 400px; overflow: hidden; background: #000;"></div>
<input type="text" id="danmu-input">
<button id="send-danmu">发送弹幕</button>
CSS 样式
.danmu-item {
position: absolute;
white-space: nowrap;
color: #fff;
font-size: 20px;
text-shadow: 1px 1px 2px #000;
}
jQuery 代码

$(function() {
// 发送弹幕
$('#send-danmu').click(function() {
const text = $('#danmu-input').val().trim();
if (text) {
createDanmu(text);
$('#danmu-input').val('');
}
});
// 回车发送
$('#danmu-input').keypress(function(e) {
if (e.which === 13) {
$('#send-danmu').click();
}
});
// 创建弹幕函数
function createDanmu(text) {
const container = $('#danmu-container');
const containerHeight = container.height();
const fontSize = 20;
// 随机颜色
const colors = ['#fff', '#ff0', '#f0f', '#0ff', '#f00', '#0f0', '#00f'];
const color = colors[Math.floor(Math.random() * colors.length)];
// 随机垂直位置
const top = Math.floor(Math.random() * (containerHeight - fontSize));
// 创建弹幕元素
const danmu = $('<div>').addClass('danmu-item')
.text(text)
.css({
color: color,
top: top + 'px',
left: container.width() + 'px'
})
.appendTo(container);
// 动画效果
danmu.animate(
{ left: -danmu.width() },
{
duration: 10000,
easing: 'linear',
complete: function() {
danmu.remove();
}
}
);
}
});
弹幕功能扩展
多轨道弹幕 可以预先定义多个轨道位置,避免弹幕重叠:
const tracks = [0, 30, 60, 90]; // 轨道位置
let currentTrack = 0;
function getNextTrack() {
currentTrack = (currentTrack + 1) % tracks.length;
return tracks[currentTrack];
}
弹幕速度控制 为不同弹幕设置不同速度:

const speed = Math.floor(Math.random() * 5000) + 5000; // 5-10秒
danmu.animate({ left: -danmu.width() }, speed, 'linear', function() {
$(this).remove();
});
弹幕碰撞检测 检测新弹幕是否会与现有弹幕碰撞:
function checkCollision(top, height) {
let collision = false;
$('.danmu-item').each(function() {
const elTop = parseInt($(this).css('top'));
const elHeight = $(this).height();
if ((top + height > elTop) && (top < elTop + elHeight)) {
collision = true;
return false; // 退出循环
}
});
return collision;
}
弹幕数据存储
从服务器获取弹幕
function loadDanmuFromServer() {
$.get('/api/danmu', function(data) {
data.forEach(function(item) {
createDanmu(item.text);
});
});
}
发送弹幕到服务器
$('#send-danmu').click(function() {
const text = $('#danmu-input').val().trim();
if (text) {
$.post('/api/danmu', { text: text }, function() {
createDanmu(text);
$('#danmu-input').val('');
});
}
});
性能优化建议
- 限制同时显示的弹幕数量,防止页面卡顿
- 使用 CSS transform 代替 left 属性动画,性能更好
- 对弹幕元素进行对象池管理,避免频繁创建销毁 DOM
- 使用 requestAnimationFrame 实现动画,更加流畅
通过以上方法可以实现一个基本的 jQuery 弹幕系统,并根据需要扩展更多功能。






