Products
GG网络技术分享 2025-03-18 16:17 0
一个简单的HTML、CSS和JavaScript代码,实现网页弹幕效果。以下是代码:
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
<title>弹幕效果</title>
<style>
#danmaku {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;
}
.danmaku-item {
position: absolute;
color: #fff;
font-size: 24px;
font-weight: bold;
white-space: nowrap;
}
</style>
</head>
<body>
<div id=\"danmaku\"></div>
<script>
const danmakuContainer = document.getElementById(\'danmaku\');
const danmakuData = [
{ text: \'弹幕1\', top: \'10%\', left: \'100%\' },
{ text: \'弹幕2\', top: \'20%\', left: \'100%\' },
{ text: \'弹幕3\', top: \'30%\', left: \'100%\' },
];
function createDanmakuItem(data) {
const item = document.createElement(\'div\');
item.classList.add(\'danmaku-item\');
item.textContent = data.text;
item.style.top = data.top;
item.style.left = data.left;
return item;
}
function animateDanmakuItem(item, duration) {
const startTime = Date.now();
const startLeft = parseFloat(item.style.left);
const endLeft = -item.offsetWidth;
function updatePosition() {
const progress = (Date.now() - startTime) / duration;
const currentLeft = startLeft - (startLeft - endLeft) * progress;
item.style.left = `${currentLeft}px`;
if (progress < 1) {
requestAnimationFrame(updatePosition);
} else {
danmakuContainer.removeChild(item);
}
}
requestAnimationFrame(updatePosition);
}
function showDanmaku(data) {
const item = createDanmakuItem(data);
danmakuContainer.appendChild(item);
animateDanmakuItem(item, 5000);
}
danmakuData.forEach(showDanmaku);
</script>
</body>
</html>这个代码实现了一个简单的弹幕效果,弹幕从右侧滑动到左侧。您可以根据需要修改样式和弹幕数据。请将此代码保存为一个HTML文件,然后用浏览器打开它以查看效果。
Demand feedback