【问题标题】:HTML Javascript - How to change image dependent on the numberHTML Javascript - 如何根据数字更改图像
【发布时间】:2015-02-09 22:32:01
【问题描述】:

我正在做一个骰子游戏作为学校的作业,我需要一些帮助。 所以我想用 javascript 将图像更改为 1 或 2 点的骰子,具体取决于我从 Math.random 得到的数字。有人知道如何做到这一点,这是我的代码。

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>dice</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <div id="die1" class="dice"><img src="dice0.png"></div>

    <div id="die2" class="dice"><img src="dice0.png"></div>

    <button onclick="rollDice()">Roll Dice</button>

    <h2 id="status" style="clear:left;"></h2>

    <script>

    function rollDice() {
        var die1 = document.getElementById("die1");
        var die2 = document.getElementById("die2");
        var status = document.getElementById("status");
        var d1 = Math.floor(Math.random() * 6) + 1;
        var d2 = Math.floor(Math.random() * 6) + 1;
        var diceTotal = d1 + d2;
        die1.innerHTML = d1;
        die2.innerHTML = d2;
        status.innerHTML = "You rolled " + diceTotal+".";
        if(d1 == d2) {
            status.innerHTML += "Doubles! You get a free turn!!";
        } else if (d1 === 3) {
            status.innerHTML += "half life 3 confirmed";
        } else if (d2 === 3)  {
            status.innerHTML += "Half Life 3 confirmed";
        } else if (d1 === 1) {

        }

    }

    </script>

</body>
</html>

【问题讨论】:

  • die1.querySelector('img').src = 'someother.img';

标签: javascript html dice


【解决方案1】:

你可以通过图片源来实现...

function rollDice() {
        var die1 = document.getElementById("die1");
        var die2 = document.getElementById("die2");
        var status = document.getElementById("status");
        var d1 = Math.floor(Math.random() * 6) + 1;
        var d2 = Math.floor(Math.random() * 6) + 1;
        var diceTotal = d1 + d2;
      
        document.getElementById("die1Img").src = "dice"+die1+".png";
       
        document.getElementById("die2Img").src = "dice"+die2+".png";
        status.innerHTML = "You rolled " + diceTotal+".";
        if(d1 == d2) {
            status.innerHTML += "Doubles! You get a free turn!!";
        } else if (d1 === 3) {
            status.innerHTML += "half life 3 confirmed";
        } else if (d2 === 3)  {
            status.innerHTML += "Half Life 3 confirmed";
        } else if (d1 === 1) {

        }

    }
<div id="die1" class="dice"><img id="die1Img" src="dice0.png"></img></div>

    <div id="die2" class="dice"><img id="die2Img" src="dice0.png"></img></div>

    <button onclick="rollDice()">Roll Dice</button>

    <h2 id="status" style="clear:left;"></h2>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    相关资源
    最近更新 更多