js實現彈幕功能的方法:1、創建html文件;2、添加html代碼架構;3、在body標簽中使用div、input、button標簽分給頁面設計效果顯示框、輸入框、彈幕提交按鈕;4、添加script標簽并寫入js代碼來實現彈幕效果;5、通過瀏覽器方式查看設計效果。
具體操作方法:
1.首先創建一個html文件。
2.在html文件中添加html代碼架構。
<!DOCTYPE html><html>
<head>
<meta charset="UTF-8">
<title>彈幕功能</title>
</head>
<body>
</body>
</html>
3.然后在html代碼架構中的body標簽里面使用div、input、button標簽分別給頁面設計一個效果顯示框、輸入框、彈幕提交按鈕。
<div id="box" class="box"></div><input type="text" id="txt" />
<button onclick="send()">發送彈幕</button>
4.在html架構中的html標簽里面添加script標簽并寫入js代碼來實現彈幕效果。
<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>
5.最后可通過瀏覽器方式閱讀html文件查看設計效果。
完整示例代碼如下:
<!DOCTYPE html><html>
<head>
<meta charset="UTF-8">
<title>彈幕功能</title>
</head>
<body>
<div id="box" class="box"></div>
<input type="text" id="txt" />
<button onclick="send()">發送彈幕</button>
</body>
<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>
</html>