最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to display the user's game score on-screen in realtime, instead of in an alert at the end? - Stack Over

programmeradmin6浏览0评论

I made a score alert and it pops up at the end of my game, stating how many coins you won (200, 300, etc.). I want it to be counting the coins while playing the game, so for it not to appear at the very end.

My question is how to get this to appear on screen; not in the format of an alert. I have a HTML div:

<div id= "score"></div> 

Here's my JavaScript that calculates how many coins have been won:

function gameOver()
{
    alert ("You got  " + score + " coins")

    document.getElementById("popup").innerHTML ="Game Over!";
    document.getElementById("popup").style.display = "block"; 

    setTimeout(messageHide, 5000); /* pop up appears when game is over */
}

var score = 0;

I made a score alert and it pops up at the end of my game, stating how many coins you won (200, 300, etc.). I want it to be counting the coins while playing the game, so for it not to appear at the very end.

My question is how to get this to appear on screen; not in the format of an alert. I have a HTML div:

<div id= "score"></div> 

Here's my JavaScript that calculates how many coins have been won:

function gameOver()
{
    alert ("You got  " + score + " coins")

    document.getElementById("popup").innerHTML ="Game Over!";
    document.getElementById("popup").style.display = "block"; 

    setTimeout(messageHide, 5000); /* pop up appears when game is over */
}

var score = 0;
Share Improve this question edited May 2, 2015 at 23:18 Danny Beckett 20.9k26 gold badges113 silver badges142 bronze badges asked May 2, 2015 at 23:11 COMCOM 711 gold badge2 silver badges8 bronze badges 1
  • Your div has an id of "score" but you're looking for an element with an id of "popup"? – James Montagne Commented May 2, 2015 at 23:15
Add a ment  | 

2 Answers 2

Reset to default 3

Since you have a div with an id of score, you need to run this line of code every time the score updates, to write it to that div:

document.getElementById('score').innerHTML = "Score: " + score;

Where score = 200 or similar.

Give your div some css like so:

#score
{
    position: absolute;
    top: /*somewhere*/;
    left: /*somewhere*/;
    z-index: 100;
}

Specify top and left where ever you want it. The z-index will keep it on top of everything else.

Combining this with the suggestion above will give you a score that updates in real time and is always visible.

You can add additional style elements to make it fancy.

发布评论

评论列表(0)

  1. 暂无评论