首先先看效果
準備好要加載的數據(jsonDM.txt)
{"ulist": [{
"username": "aaaa",
"info": "不錯",
"time": "1528297619"
},
{
"username": "bbbb",
"info": "垃圾玩意",
"time": "1528297619"
}
]
}
HTML
<!DOCTYPE html>
<!-- saved from url=(0045)http://passport.jikexueyuan.com/sso/reg_phone -->
<html lang="zh-cn"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="renderer" content="webkit">
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>弹幕</title>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script src="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="stage">
<div id="player"></div>
<div class="sendPannel">
<input type="text" autofocus="">
<input type="button" value="發 送">
</div>
</div>
<script type="text/javascript" src="js/jquery-3.3.1.min"></script>
<script type="text/javascript" src="js/script"></script>
</body>
</html>
JS
var infoId = 0;
var nowPlayCount = 0;
var infoBgSet = Array("#7b2e2e", "#9c8307", "#078f9c", "#4b4d8a", "#8a4b4b");
function sendInfo(uname, info, delay) {
setTimeout(function() {
infoId++;
$("<span id='info_" + infoId + "'>" + uname + ":" + info + "</span>").appenTo("#player");
$("#info_" + infoId).css("background", getColor());
$("#info_" + infoid).css("top", (nowPlayCount % 4) * 40 + "px");
nowPlayCount++;
$("#info_" + infoId).animate({ right: "1004px" }, 10000, function() {
nowPlayCount--;
});
}, delay);
}
//隨機獲取顔色
function getColor() {
return infoBgSet[Math.floor(Math.random() * (infoBgSet.length - 1) + 1)];
}
//綁定發送按鈕事件
$(".sendPannel input[type='button']").on("click", function() {
if ($(".sendPannel input[type='text']").val() != '') {
sendInfo("ASMITA", $(".sendPannel input[type='text']"), 3000);
}
});
//加載數據
function loadData() {
$.ajax({
url: "jsonDM.txt",
dataType: "json",
success: function(data) {
var ulist = data.ulist.sort(function(a, b) {
return a.time.localeCompare(b.time);
});
$(ulist).each(function(i, v) {
sendInfo(v.uname, v.info, (i + 1) * 3000);
})
},
error: function(e) {
console.log(e);
}
});
};
//初始化
$(document).ready(function() {
loadData();
});