基于JavaScript与jQuery实现简易弹幕特效

作者:纸飞机

时间:2026-10-23

浏览:566

本文介绍使用HBuilder编译环境,结合jQuery-2.0.3.js库实现简易弹幕效果的具体代码。通过CSS控制样式与jQuery动画函数控制运动,展示弹幕生成与移除机制,供前端学习者参考。

文章目录

弹幕特效实现概述

本文分享了一段使用JavaScript实现弹幕特效的完整代码示例,供读者参考学习。

开发环境采用HBuilder进行编译,旨在演示最基础的弹幕运行效果,欢迎有经验的前辈提出改进建议。

代码实现中明确引用了jquery-2.0.3.js库文件。

核心代码结构与逻辑


<!DOCTYPE html> 
<html> 
 <head> 
 <meta charset="utf-8" /> 
 <title></title> 
 </head> 
 
 <style type="text/css"> 
 *{ 
 padding: 0; 
 margin: 0; 
 } 
 .shooter{ 
 width: 600px; 
 height: 60px; 
 /*background: black;*/ 
 margin: 0 auto; 
 } 
 .shooter input{ 
 width: 300px; 
 height: 40px; 
 border: none; 
 border-radius: 7px; 
 box-shadow: 0 0 8px rgba(182,195,214,0.6)inset; 
 padding-left: 15px; 
 margin-top: 10px; 
 } 
 .shooter button{ 
 width: 80px; 
 height: 40px; 
 border: none; 
 margin-left: 10px; 
 background-color:#339B53; 
 border-radius:8px; 
 color: white; 
 cursor: pointer; 
 } 
 
 .shooter button:hover{ 
 font-size: 14px; 
 background:#008000; 
 } 
 .content{ 
 width: 100%; 
 height: 600px; 
 background: gray; 
 position: relative; 
 overflow: hidden; 
 } 
 
 .bullet{ 
 position: absolute; 
 /*right: 0;*/ 
 /*left:1600px;*/ 
 word-break: keep-all; 
 /*不让单词折行*/ 
 
 
 } 
 
 </style> 
 
 <body> 
 <div class="shooter"> 
 
 <input type="text"/> 
 <button>发射</button> 
 
 </div> 
 <div class="content"> 
 
 </div> 
 <script type="text/javascript" src="js/jquery-2.0.3.js" ></script> 
 
 <script type="text/javascript"> 
 $("button").click(function(){ 
  
 var msg = $("input").val(); 
 //取出输入框内容 
  
 if(msg.length > 15){ 
  
  alert("字数不得超过15个!"); 
  return; 
 } 
  
 var bullet = $("<div>"); 
 //生成一条弹幕 
 bullet.text(msg); 
 //将输入框内容放置到div中 
 bullet.addClass("bullet"); 
 //为bullet这个div添加样式bullet 
 bullet.css("top",Math.round(Math.random()*500)); 
 //随机设置弹幕位置 
 bullet.css("left","1600px"); 
 bullet.css("font-size",Math.round(Math.random()*60)+12+"px"); 
 bullet.css("color","rgb("+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+")"); 
// alert(window.getComputedStyle(bullet,null).width); 
 bullet.animate({ 
  left:-1000//此处视为bug,应该随着弹幕的长短而变化 
 },Math.round(Math.random()*9000)+1000,"linear", function(){ 
  bullet.remove(); 
  //当运动结束时,删除弹幕 
 }); 
  
 $(".content").append(bullet); 
 //将弹幕添加到屏幕中 
  
  
 }); 
 </script> 
 </body> 
</html>

效果展示与注意事项

下方展示了实际的弹幕运行效果。需要注意的是,在谷歌浏览器中显示的白色线条可能不易察觉,但在屏幕录制过程中可以观察到,此处存在一个显示上的小瑕疵。

弹幕特效实现概述

以上内容为本文的全部分享,希望能为读者的学习提供一定帮助,同时也感谢大家对本平台的支持。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章