我一直在“编写”一个游戏,其中涉及您收集资源,然后将这些资源花在一些东西上,然后创建更多该资源(当我完成时,它会更有趣)。
无论如何,我的问题是,在购买了太多可以创造更多资源的东西后,我无法找到一种方法来阻止资源数量变为负值。我需要某种方法来禁用该按钮。
我还想知道如何显示树木总数的百分比:)
为了方便起见,这里是代码...
<!DOCTYPE html>
<html>
<head>
<title>Game</title>
<script>
function collectSeeds() {
document.getElementById("Seeds").stepUp(1);
}
function plantTree() {
document.getElementById("Seeds").stepDown(10);
document.getElementById("Trees").stepUp(1);
}
function plantTrees10() {
document.getElementById("Seeds").stepDown(100);
document.getElementById("Trees").stepUp(10);
}
</script>
</head>
<body>
<button onclick="collectSeeds()">Collect Seeds</button>
<button type="button" id="plantTree"
onClick="myTimer = setInterval(collectSeeds, 1000); plantTree();">Plant Tree</button>
<button
onClick="plantTrees10(); myTimer = setInterval(collectSeeds,100);">Plant Trees (10)</button>
<p>Seeds
<br/>
<input type="number" id="Seeds" disabled></input>
<p>Trees
<br/>
<input type="number" id="Trees" disabled></input>
<div style="position: fixed; bottom: 0; right: 0;">Progress:</div>
</body>
</html>
最佳答案
按照 documentation 中的说明将最小值和最大值添加到字段中
您可能也想在某个地方留言。
最后在再次使用之前清除间隔 - 我重写了脚本,使其不显眼且通用。
var myTimer; // make global in scope
function collectSeeds() {
document.getElementById("Seeds").stepUp(1);
}
function plantTree(but) {
var nofSeeds = parseInt(but.getAttribute("data-nofseeds"), 10),
availableSeeds = parseInt(document.getElementById("Seeds").value, 10);
if (availableSeeds < nofSeeds) {
console.log(availableSeeds + " not enough, " + nofSeeds + " needed"); // give some message somewhere
return;
}
console.log(nofSeeds)
document.getElementById("Seeds").stepDown(10 * nofSeeds);
document.getElementById("Trees").stepUp(nofSeeds);
}
window.onload = function() {
var plantButtons = document.querySelectorAll(".plantTree");
for (var i = 0; i < plantButtons.length; i++) {
plantButtons[i].onclick = function() {
clearInterval(myTimer); // only have one timer running
myTimer = setInterval(collectSeeds, 1000);
plantTree(this);
}
}
}
<button onclick="collectSeeds()">Collect Seeds</button>
<button type="button" class="plantTree" data-nofseeds="1">Plant Tree</button>
<button type="button" class="plantTree" data-nofseeds="10">Plant Trees (10)</button>
<p>Seeds
<br/>
<input type="number" min="0" max="1000" id="Seeds" disabled />
</p>
<p>Trees
<br/>
<input type="number" id="Trees" disabled />
</p>
<div style="position: fixed; bottom: 0; right: 0;">Progress:</div>
关于javascript - 如何阻止数字变成负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41084150/