看完jquery的一些知识,想拿个小项目来练练手,看到知乎上说可以写个弹幕墙,于是乎,找了一个相关的项目来学习,并做了小改动
原来的网址是:http://blog.csdn.net/qq_32623363/article/details/75042028
原来的博主的思路说的挺清楚明白的。
下面贴个代码:
barrageWall.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String basePath = request.getContextPath(); //获得根路径
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="<%=basePath%>/css/barrageWall.css" type="text/css">
<script type="text/javascript" language="javascript" src="<%=basePath %>/js/jquery-1.9.1.js"></script>
<script type="text/javascript" language="javascript" src="<%=basePath %>/js/barrageWall.js"></script>
<title>弹幕墙</title>
</head>
<body>
<div id="wall"></div>
<div id="bar">
<input type="text" id="comment" placeholder="输入文字">
<input type="button" class="btn" id="send" value="发送弹幕">
<input type="button" class="btn" id="close" value="关闭弹幕">
</div>
</body>
</html>
barrageWall.css
html, body{
margin: 0;
padding: 0;
-webkit-user-select: none;
-moz-user-select: none;
-khtml-user-select: none;
-ms-user-select: none;
-user-select: none;
overflow: hidden;
width: 800px;
height: 500px;
}
body{
box-sizing: border-box;
}
#wall{
border: 2px solid #F5F5F5;
width: 700px;
height: 400px;
}
#comment{
width: 200px;
height: 30px;
font-size: 12px;
font-family: "Microsoft 'Yahei'";
color: black;
}
#bar{
margin-top: 20px;
}
barrageWall.js
var start = true;
$(document).ready(function(){
var screen = $("#wall");
var width = screen.width(); //获得弹幕墙的宽高
var height = screen.height();
$("#send").click(function(){
var msg = $("#comment").val(); //获得输入的值
$("#comment").val(""); //清空文本
msgObj = $("<div>"+msg+"</div>"); //DOM节点
screen.append(msgObj);
move(msgObj);
if(start == false){
start = true;
$("#close").val("关闭弹幕");
}
});
$("#close").click(function(){
if(start == true){
start = false;
$("#close").val("开启弹幕");
screen.empty();
}
else if(start == false){
start = true;
$("#close").val("关闭弹幕");
}
});
var move = function(obj){
var time = 20000+Math.random()*10000; //时间
var top = Math.random()*(height -20) + 10; //为了不让文本超出弹幕框
obj.css({
display: "inline",
position: "absolute"
});
var begin = Math.random() < 0.5 ? screen.width()-obj.width() : 0; //从左边还是右边轮出
obj.css({
color: getRandomColor,
top: top,
left: begin
});
if(begin!=0){
obj.animate({
left: "-"+begin+"px" //从右边轮出
}, time, function(){
obj.remove();
});
}
else{
obj.animate({
left: width - obj.width()+"px" //从左边轮出
}, time, function(){
obj.remove();
});
}
}
var getRandomColor = function(){
return '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).substr(-6); //随机颜色
}
});