JS实现的视频弹幕效果示例

<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <title>斗鱼弹幕</title> <style> html,body{font-size:10px;overflow:hidden;margin:0;padding:0;} #box{width:100%;height:100%;} #dm{width:100%;height:90vh;background:#E8F1F5;} #dm span{width:auto;height:3rem;font-size:2rem;line-height:2rem;position:absolute;white-space:nowrap;} #idDom{width:100%;height:10vh;background:#666;position:absolute;bottom:0;display:flex;align-items:center;justify-content:center;} #content{width:50rem;height:10vh;display:flex;align-items:center;justify-content:center;} .title{font-size:2.2px rein;color:#fff;line-height:#ccc;} .text{width:30rem;height:2.5rem;border:none;border-radius:.5rem;font-size:1.4rem;margin:0 .5rem;padding:0 1rem;} .btn{width:6rem;height:3rem;border:none;background:red;color:#fff;} </style> </head> <body> <div> <div></div> <div> <div> <p>吐槽:</p> <input type="text" placeholder="请输入你想说的话" /> <button type="button">发射!</button> </div> </div> </div> <script langugae="javascript"> var timer; var btn = document.getElementById('btn'); btn.onclick = function() { addBarrage();} document.onkeydown = function(evt) {var event = evt || window.event;if (event.keyCode == 13) {addBarrage();}} var colors = ['#2C3E50', '#FF0000', '#1E87F0', '#7AC84B', '#FF7F00', '#9B39F4', '#FF69B4'];//弹幕颜色库 function addBarrage() { clearInterval(timer); var text = document.getElementById('text').value; document.getElementById('text').value = ""; var index = parseInt(Math.random() * colors.length); //随机弹幕颜色 var screenW = window.innerWidth; var screenH = dm.offsetHeight; var max = Math.floor(screenH / 40); var height = 10 + 40 * (parseInt(Math.random() * (max + 1)) - 1); var span = document.createElement('span'); span.style.left = screenW + 'px'; span.style.top = height + 'px'; span.style.color = colors[index]; span.innerHTML = text; var dmDom = document.getElementById('dm'); dmDom.appendChild(span); timer = setInterval(move, 10); } function move() { var arr=[]; var oSpan=document.getElementsByTagName('span'); for(var i=0;i<oSpan.length;i++){ arr.push(oSpan[i].offsetLeft); arr[i] -= 2; oSpan[i].style.left = arr[i]+'px'; if(arr[i]<-oSpan[i].offsetWidth){ var dmDom=document.getElementById('dm'); dmDom.removeChild(dmDom.childNodes[0]); } } } </script> </body> </html>

运行效果如下图所示:

JS实现的视频弹幕效果示例

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具,测试代码运行效果。

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript动画特效与技巧汇总》、《JavaScript页面元素操作技巧总结》、《JavaScript运动效果与技巧汇总》、《JavaScript图形绘制技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript数学运算用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/71609e8a6d21e03188fee26af1063d85.html