0

I'm creating a fight log where combat information will go inside a div box that holds about 15 lines. After 16+ lines, the text goes through the box and starts heading south.

Is there a way in Javascript to say "hey, after 15 lines, create a new line, and delete the last line!".

I'm thinking I would set this up with arrays. Would that be correct? Where I would say something along the lines of.. 15 elements, and after 16 elements, delete last element and push a new element?

This is all I have for code:

document.getElementById("log").innerHTML += "Fight Log";

After 15+ of these, it goes outside the DIV Fight Log box.

4

3 回答 3

1

尝试将这些消息添加到数组中,并每次重新呈现所有消息。这样你就可以使用数组方法来管理消息的数量:

var log = [],
  messageElem = document.getElementById("log");    

function addMessage(message) {
  log.push(message);
  while (log.length > 16) {
    log.shift();
  }
  messageElem.innerHTML = log.join("\n");
}


... then later ...

addMessage('Fight Log');
于 2013-09-16T23:26:11.377 回答
0

这取决于你的 div 是怎样的,它可能有固定的大小。尝试指定 style="overflow:auto;" 因此,一旦消息超出范围,它就会显示滚动条。

于 2013-09-16T23:30:10.440 回答
0

这是它的 JSFiddle

包装您的日志消息span,使其变成一个可选择的 DOM 项。15+时选择最后一个并删除它。这是如何完成的。

function addMessage(message) {
    var logElement = document.getElementById('log');
    var elements = document.getElementById('log').getElementsByTagName('span');
    var length = elements.length;
    if(length >= 15) {
        logElement.removeChild(elements[length-1]);
    }
    logElement.innerHTML += "<span>" + message + "</span>";
}

for(var i=1; i<30; i++) {
    addMessage('Figth Log ' + i);
}
于 2013-09-17T00:04:30.793 回答