實作方法:1、建立html檔案;2、新增html程式碼架構;3、在body標籤中使用div、input、button標籤分給頁面設計效果顯示框、輸入框、彈幕提交按鈕;4、新增script標籤並寫入js程式碼來實現彈幕效果;5、透過瀏覽器方式查看設計效果。
js怎麼實作彈幕功能
#特定操作方法:
##1.先創建一個html檔。 2.在html檔案中加入html程式碼架構。<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>弹幕功能</title> </head> <body> </body> </html>
<div id="box" class="box"></div> <input type="text" id="txt" /> <button onclick="send()">发送弹幕</button>
<style> function $(str) { return document.getElementById(str); } function send() { var word = $('txt').value; var span = document.createElement('span'); var top = parseInt(Math.random() * 500) - 20; var color1 = parseInt(Math.random() * 256); var color2 = parseInt(Math.random() * 256); var color3 = parseInt(Math.random() * 256); var color = "rgb(" + color1 + "," + color2 + "," + color3 + ")"; top = top < 0 ? 0 : top; span.style.position = 'absolute'; span.style.top = top + "px"; span.style.color = color; span.style.left = '500px'; span.style.whiteSpace = 'nowrap'; var nub = (Math.random() * 10) + 1; span.setAttribute('speed', nub); span.speed = nub; span.innerHTML = word; $('box').appendChild(span); $('txt').value = ""; } setInterval(move, 200); function move() { var spanArray = $('box').children; for (var i = 0; i < spanArray.length; i++) { spanArray[i].style.left = parseInt(spanArray[i].style.left) - spanArray[i].speed + 'px'; } } </style>
弹幕功能 <div id="box" class="box"></div> <input type="text" id="txt" /> <button onclick="send()">发送弹幕</button> <script> function $(str) { return document.getElementById(str); } function send() { var word = $('txt').value; var span = document.createElement('span'); var top = parseInt(Math.random() * 500) - 20; var color1 = parseInt(Math.random() * 256); var color2 = parseInt(Math.random() * 256); var color3 = parseInt(Math.random() * 256); var color = "rgb(" + color1 + "," + color2 + "," + color3 + ")"; top = top < 0 ? 0 : top; span.style.position = 'absolute'; span.style.top = top + "px"; span.style.color = color; span.style.left = '500px'; span.style.whiteSpace = 'nowrap'; var nub = (Math.random() * 10) + 1; span.setAttribute('speed', nub); span.speed = nub; span.innerHTML = word; $('box').appendChild(span); $('txt').value = ""; } setInterval(move, 200); function move() { var spanArray = $('box').children; for (var i = 0; i < spanArray.length; i++) { spanArray[i].style.left = parseInt(spanArray[i].style.left) - spanArray[i].speed + 'px'; } } </script>
以上是js怎麼實現彈幕功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!