js实现弹幕发送

js发送实现弹幕

使用原生js实现模拟简单弹幕效果,原理为每点击一次,input的内容生成一个span标签,生成的span的位置在右边框那里,高度时随机的,颜色也是随机的。
在这里插入图片描述
这个里面实现的话,定时器不能只有一个,而是要给每一个span都开启一个新的定时器,这样才不会影响动画的执行。并且需要当弹幕出去的时候清除掉这个span。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}

			.dm-box {
				width: 1500px;
				height: 700px;
				border: 1px #000000 solid;
				margin: 0 auto;
				position: relative;

			}

			.sd-box {
				width: 600px;
				height: 100px;
				margin: 0 auto;
				text-align: center;
				font-size: 0;
				margin-bottom: 0;
				border: 1px black solid;
			}

			.send-box {
				border: 1px red solid;
				display: inline-block;
				margin-top: 35px;
				position: relative;
			}

			.send-box .ct {
				width: 300px;
				height: 26px;
				outline: none;
				line-height: 30px;

			}

			.send-box .bt {
				width: 70px;
				height: 30px;
				line-height: 30px;
				background-color: red;
				border: none;
				outline: none;
				cursor: pointer;

			}

			span {
				position: absolute;
				top: 0;
				left: 600px;
			}
		</style>
		<script type="text/javascript">
			function $(id) {
				return document.getElementById(id);
			}
			window.onload = function() {
				$('btn').onclick = function() {
					var pos = 1400;
					var height = parseInt(Math.random() * 650);
					var color = '#' + Math.floor(Math.random() * 0xffffff).toString(16);
					var span = document.createElement('span');
					span.style.top = height + 'px';
					span.style.color = color;
					span.style.left = 100 + 'px';
					span.innerHTML = $('content').value;
					$('dm').appendChild(span);
					var timer = setInterval(function() {
						pos--;
						span.style.left = pos + 'px';
						if (parseInt(span.style.left) < 0) {
							clearInterval(timer);
							$('dm').removeChild(span);
						}
					}, 3)
				}
			}
		</script>
	</head>

	<body>
		<div id="dm" class="dm-box"></div>
		<div id="box" class="sd-box">
			<div id="send" class="send-box">
				<input type="text" id="content" class="ct" />
				<input type="button" id="btn" value="发送" class="bt" />
			</div>

		</div>
	</body>
</html>

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值