我正在制作骰子游戏作为学校作业,我需要一些帮助。 所以我想用 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>
最佳答案
您可以通过图像源来完成...
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>
关于javascript - HTML Javascript - 如何根据数字更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27422885/