JS实现的视频弹幕效果示例
sbdx 人气:0本文实例讲述了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 class="box" id="box"> <div id="dm"></div> <div class="idDom" id="idDom"> <div id="content"> <p class="title">吐槽:</p> <input type="text" class="text" id="text" placeholder="请输入你想说的话" /> <button type="button" class="btn" id="btn">发射!</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>
运行效果如下图所示:
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.softyun.net/code/HtmlJsRun,测试代码运行效果。
希望本文所述对大家JavaScript程序设计有所帮助。
加载全部内容