var danmu = { play_width : 0, //銀幕寬 play_height : 0, //銀幕高 msg_stu : {}, //彈幕結構 msg_queue : [], //彈幕隊列 play_screen : null, addmsg : function(text){ mathHeight = Math.round(Math.random()*this.play_height); speed = Math.round(5+Math.random()*20); var msg = { 'left' : this.play_width, 'top' : mathHeight, 'text' : text, 'speed' : speed, }; this.msg_queue.push(msg); }, play : function(){ var i = 0; for(var msg in this.msg_queue){ console.log(i); if(this.msg_queue[i].left<(0-this.play_width)){ this.removemsg(i); }else{ this.playmsg(i); } i++; } }, playmsg : function(i){ bullet = document.getElementById('zidan_'+i); if(bullet!=undefined){ //子彈飛 this.msg_queue[i].left -= this.msg_queue[i].speed; bullet.style.left = this.msg_queue[i].left+'px'; bullet.style.top = this.msg_queue[i].top+'px'; }else{ //建立子彈 b = document.createElement("font"); b.id = 'zidan_'+i; msg = this.msg_queue[i]; b.style.position = 'absolute'; b.style.color = '#fff'; b.style.left = msg.left+'px'; b.style.top = msg.top+'px'; b.innerHTML = msg.text; this.play_screen.appendChild(b); } }, removemsg : function(i){ bullet = document.getElementById('zidan_'+i); bullet.style.left = this.play_width+'px'; this.msg_queue[i].left = this.play_width; }, init : function(playid,btnid,textid){ this.play_width = document.getElementById(playid).offsetWidth; this.play_height = document.getElementById(playid).offsetHeight; this.play_screen = document.getElementById(playid); this.play_screen.style.position = 'relative'; document.getElementById(btnid).onclick = function(){ danmu.addmsg(document.getElementById(textid).value); console.log(danmu.msg_queue); }; setInterval(function(){ danmu.play(); },50); } }; danmu.init('tangmu','inputBtn','inputText');
<div class="danmuBox"><div id="tangmu">2</div></div> <div class="form"> <form> <input type="text" placeholder="愛要大聲說出來..." value="" maxlength="30" id="inputText" class="textarea" id="text"> <input type="button" value="向世界發佈" class="submit inputBtn" id="inputBtn"> <input type="reset" value="不發了- -#" name="reset" class="reset inputBtn"> </form> </div>