效果图
实现思路
想要实现这种效果,从图上看我们得有三个div盒子,第一个div就是全屏的效果,其中又包括颜色为灰色的div盒子。如果文字、输入框、按钮想要同时居中,也需要把它们放在一个盒子中。
HTML
<div id="boxDom">
<div id="idDom">
<div class="smallBox">
<p class="title">吐槽:</p>
<input type="text" class="text"/>
<button id="btn">发射</button>
</div>
</div>
</div>
CSS
<style>
body {
margin: 0;
padding: 0;
}
#boxDom {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
}
#idDom {
width: 100%;
height: 100px;
background-color: #666;
position: fixed;
bottom: 0px;
}
.smallBox {
display: inline-block;
width: 430px;
height: 40px;
position: absolute;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
margin: auto;
}
.title {
display: inline;
font-size: 20px;
color: #ffffff;
text-align: center;
}
.text {
height: 20px;
border-radius: 5px;
}
span {
position: fixed;
right: -500px;
}
</style>
JS代码
$(function () {
//设置弹幕文字颜色
var colors = ["red", "green,", "pink", "orange"];
$("#btn").click(function () {
//随机获取颜色数组
var randomColor = parseInt(Math.random() * colors.length);
//发送的弹幕出现的位置,也进行随机化
var randomY = parseInt(Math.random() * 400);
//发送的弹幕文字使用<span>包括起来
$("<span></span>")
//将文本框中的内容写入到span中
.text($(".text").val())
//给文字设置颜色
.css("color", colors[randomColor])
//将文字向左靠近,刚开始肯定是隐藏的,注意如果css中不写span样式的话,不会达到我们想要的效果
.css("left", "1400px")
//这里就是文字距离顶部的位置,随机的
.css("top", randomY)
//最后我们在设置文字的动画效果
//这里分别是终点,显示的时间长短,速度是匀速,最后回调函数写,文字到达终点的时候就将它删除
.animate({left: -500}, 6000, "linear", function () {
$(this).remove();
})
//写了以上效果最后记得把它添加到boxDom中。
.appendTo("#boxDom");
//发送后,清空文本内容。
$(".text").val("");
});
})