大家对B站不陌生吧,特别是他的弹幕系统是很多网站都在模仿的,但是你知道他是怎么制作的吗?今天小猿圈web前端讲师就用jQuery实现弹幕评论效果,希望对你有所启发。
首先第一步:布局
CSS部分
<style>
*{padding: 0;margin: 0;
font-family: "微软雅黑";
font-size: 16px;
}
html,body{
width:100%;
height: 100%;
}
.box{
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
#bottom {
width: 100%;
height: 100px;
background-color: #666;
position:fixed;
bottom:0px;
}
.content {
width: 430px;
height: 40px;
margin: 30px auto;
}
.title {
font-size: 22px;
color: #fff;
vertical-align: bottom;
display: inline;
}
#text {
width:300px;
height: 30px;
border: none;
border-radius: 5px;
}
#btn1 {
width: 60px;
height: 30px;
border: none;
margin-left: 2px;
background-color: red;
color: #fff;
}
span {
position: absolute;
font-size: 30px;
line-height: 30px;
white-space: nowrap;
}
</style>
下面是HTML部分
<body>
<div id="box" class="box">
<div id="bottom">
<div class="content">
<p class="title">吐槽:</p><input type="text" id="text"><button id="btn1">发射</button>
</div>
</div>
</div>
</body>
注意span别忘了加定位,否则无法做动画
jQuery代码实现
<script src="jquery-1.12.4.js"></script>
<script>
$(function(){
var colors=["red","green","blue","pink","purple","cyan","hotpink","#000"]
$("#btn1").click(function(){
var randomColors=parseInt(Math.random()*colors.length);
var randomY=Math.random()*400;
//console.log(randomY);
$("<span></span>")
.text($("#text").val())
.css("color",colors[randomColors])
.css("left",$(window).width())
.css("top",randomY)
.animate({left:-500},10000,"linear",function(){
$(this).remove();
})
.appendTo("#box");
$("#text").val("");
})
$("#text").keyup(function(e) {
if (e.keyCode==13) {
$("#btn1").click();
}
})
})
</script>
代码看起来很简单主要有随机颜色、随机位置的弹幕效果。新建span设置出现的X坐标和Y坐标,动画的效果和持续时间。以及发送完弹幕之后,输入框清空和给输入框绑定事件,按回车键也能发送弹幕。
需要注意的是弹幕动画的回调函数,动画执行结束后,一定要让这个span自我删除。
以上就是小猿圈web前端讲师对于jQuery实现弹幕评论效果的简单介绍,相信你也看会了很多吧,那就赶快行动去练习一下吧,记住学习前端不仅需要看文档看视频,还要的就是多多的练习前端自学交流群:820024416,这样才能记的牢固,视频可以到小猿圈去观看的,里面有最全最新的视频。
网友评论