jQuery实现简单的弹幕效果
效果演示
jQuery,HTML实现简单的弹幕效果
HTML代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>弹幕dome</title>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
<script type="text/javascript" src="js/jquery-1.11.0.js" ></script>
<script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="bulletbox" id="bulletbox">
<div class="bulletboxmin" id="bulletboxmin"></div>
<div class="bulletbot">
<div class="bulletbotmin">
<p>吐槽:</p>
<input type="text" class="text" id="text" placeholder="火力已加满..." />
<button type="button" class="btn" id="btn" >发布</button>
</div>
</div>
</div>
</body>
</html>
css代码
html,body{margin: 0px; padding: 0px; width: 100%; height: 100%; font-family: "微软雅黑";font-size: 100%;}
/* 弹幕 */
.bulletbox{width: 100%;height: 100%;position: relative;background-color: #FFFFFF;overflow: hidden;}
.bulletboxmin{width: 100%;box-sizing: border-box;height: calc(100% - 130px);}
/* bulletbot */
.bulletbot{width: 100%;box-sizing: border-box;position: fixed;bottom: 0;left: 0;background-color: #404060;display: flex;display: -webkit-flex;-webkit-justify-content: center;justify-content: center;}
.bulletbotmin{display: flex;display: -webkit-flex;-webkit-align-items: center;align-items: center;height: 130px;}
.bulletbotmin p{font-size: 20px;color: #FFFFFF;margin-right: 10px;}
.bulletbotmin input{display: block;width: 400px;height: 50px;outline: none;background-color: #FFFFFF;border: none;border-top-left-radius: 10px;border-bottom-left-radius: 10px;box-sizing: border-box;padding: 0 20px;font-size: 16px;color: #333333;}
.bulletbotmin button{display: block;width: 140px;height: 50px;background-color: #0099CC;border: none;outline: none;border-top-right-radius: 10px;border-bottom-right-radius: 10px;font-size: 16px;color: #FFFFFF;cursor: pointer;}
.bulletbox span{width: 300px; height: 40px; position: absolute; overflow: hidden;font-size: 20px;color: #AFEEEE; line-height: 40px;white-space: nowrap; cursor: pointer;font-weight: bold;}
jQuery代码
$(function(){
$("#btn").click(function(){
//评论产生的随机高度
var pageH=parseInt(Math.random()*300);
//创建span元素(弹幕条)
var newSpan=$("<span></span>");
//获取用户输入的字符串
var str=$("#text").val();
//为新元素赋值
newSpan.text(str);
//每次发表后清空输入框
$("#text").val("");
//设置弹幕出现位置
newSpan.css("left","1400px");
newSpan.css("top",pageH);
//设置弹幕颜色
newSpan.css("color",randomColor());
//弹幕动画
newSpan.animate({"left":-500},10000,"linear",function(){
$(this).remove();
})
//弹幕添加
newSpan.appendTo("#bulletboxmin")
})
//定义一个随机生成颜色的方法
function randomColor(){
var colorArr=['pink','red','blue','puper','orange','black','DarkMagenta','DoderBlue','DeepSkyBlue','CadetBlue','DarkSlateGray','Yellow','Tomato',' RosyBrown'];
var color=parseInt(Math.random()*colorArr.length);
return colorArr[color];
}
})