【发布时间】: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