js

js怎么实现弹幕功能

小新
849
2021-04-20 17:15:52
栏目: 编程语言

js实现弹幕功能的方法: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>

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>


0
看了该问题的人还看了