弹幕制作小练习
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .container{ width: 500px; height: 300px; background: black; position: relative; } span{ font-size: 16px; color: white; /* transition: all 3s; */ position: absolute; width: 500px; overflow: hidden; } </style> </head> <body> <div class="container"> </div> <div class="comment"> <input type="text" id="sendText" placeholder="来几条弹幕吧~~"> <button id="sendBtn">发送</button> </div> <script> let video=document.getElementsByTagName('video'); let container=document.getElementsByClassName('container')[0]; //随机函数 let random = function (start,end){ return Math.floor(Math.random()*(end-start+1))+start; } let wordMove = function(){ let span = document.createElement("span"); span.innerHTML = sendText.value.substring(0,50); sendText.value = ""; let speed = random(5,10); //span标签开始移动的水平位置 span.style.left = container.offsetWidth + container.offsetLeft+ "px"; console.log(span.style.left,); //开始移动的垂直位置 let totalHeight = container.offsetTop + 300; span.style.top = random(container.offsetTop + 10, totalHeight -15) +"px"; // console.log(container); container.appendChild(span); let stopTimer = setInterval(function(){ span.style.left = parseInt(span.style.left)-speed+ "px"; //50ms span移动一次 //<0 后终止计时器 并移除span标签 if(parseInt(span.style.left)<0){ clearInterval(stopTimer); container.removeChild(span); } },50) } sendBtn.onclick = wordMove; document.onkeydown = function (e){ if(e.keyCode === 13){ wordMove(); } } </script> </body> </html>