如何使用 JavaScript 更新进度条的值?

所以我想做的是根据某些条件使用进度条在视觉上降低生命值。


const bgURLs = {

    "Air": "https://media1.giphy.com/media/RK7pdHVS4N7he/source.gif",

    "Fire": "https://i.gifer.com/5NOX.gif",

    "Water": "https://steamuserimages-a.akamaihd.net/ugc/947328402825377319/20625B881E545FF98AF1A48BAC52D4CBD207101B/",

  };



let options = document.getElementById("Options")

let computerChoice = getComputerChoice()

let playerChoice = ''   



let updatePlayerChoice = Options.addEventListener("click", function(e) {

  playerChoice = e.target.id;    

  return playerChoice

})



function getComputerChoice() {

  const keys = Object.keys(bgURLs);    

  const randomIndex = [Math.floor(Math.random() * keys.length)]   

  const compChoice = keys[randomIndex] 

  return compChoice 

}


// image shows up after clicked function

Options.addEventListener("click", function(e) { 

  let tgt = e.target; 

  let player = document.getElementById("Player")

  let computer = document.getElementById("Computer")

  if (tgt.classList.contains("element")) {   

    player.style.backgroundImage = 'url(' + bgURLs[tgt.id] + ')';   

    computer.style.backgroundImage = 'url(' + bgURLs[computerChoice] + ')';

  }

})

 


let playerHealth = document.getElementById("player-health").getAttribute("value")

let computerHealth = document.getElementById("computer-health").getAttribute("value");



function compareChoices() {

  if (playerChoice === "Fire" & computerChoice === "Water") {

     playerHealth -= 25

  } else if (playerChoice === "Fire" & computerChoice === "Air") {

     playerHealth -= 25

  } else if (playerChoice === "Fire" & computerChoice === "Fire") {

     playerHealth -= 25

  }

}

我认为主要问题是我对最后一个函数的逻辑。我的代码所做的是使用事件监听器监听playerChoice,然后它给我返回值,我可以用它来将答案与计算机选择进行比较。这部分代码肯定有效。但我似乎无法根据这些条件之一来定位值属性来更新它。当我尝试 console.log playerHealth 或 computerHealth 查看是否发生任何情况时,它仍然保持在 100,这是我设置的最大值。我的代码不应该根据我的条件在视觉上降低进度条吗?

https://jsfiddle.net/Jbautista1056/bLs0tyef/


阿波罗的战车
浏览 94回答 2
2回答

繁星点点滴滴

您遇到了几个问题,从引用错误的变量(Options,而不是options)到评估猜测后没有实际更新进度条值。您还有很多不必要的代码。由于我不确定你的游戏中什么打败了什么,你必须调整这组条件,if/else if并为计算机失去/获得分数添加更多。但是,现在,如果您重复单击fire或water,您会看到一些操作。您添加的条件和分数调整越简洁,进度条的响应速度就越快。有关详细信息,请参阅下面的内联评论:const bgURLs = {&nbsp; &nbsp; "Air": "https://media1.giphy.com/media/RK7pdHVS4N7he/source.gif",&nbsp; &nbsp; "Fire": "https://media2.giphy.com/media/AHeTfHgVFPHgs/source.gif",&nbsp; &nbsp; "Water": "https://steamuserimages-a.akamaihd.net/ugc/947328402825377319/20625B881E545FF98AF1A48BAC52D4CBD207101B/"};// Don't set variables equal to DOM element properties directly// because every time you want a different property, you have to// query the DOM for the same element over and over. Just get a// reference to the element and when you want a property, just// get it from that element reference.let player = document.getElementById("Player");let computer = document.getElementById("Computer");let playerProg = document.getElementById("player-health");let computerProg = document.getElementById("computer-health");let options = document.getElementById("Options");// These need to be declared so they can be accessed throughout// the game, but their values won't be known until an event happenslet playerChoice = null;let computerChoice = null;let playerHealth = 100;let computerHealth = 100;function getComputerChoice() {&nbsp; let random = Math.floor(Math.random() * Object.keys(bgURLs).length);&nbsp; computerChoice = Object.keys(bgURLs)[random];&nbsp; return computerChoice;}// You had Options here, but your variable is optionsoptions.addEventListener("click", function(e) {&nbsp;&nbsp; if (e.target.classList.contains("element")) {&nbsp;&nbsp; &nbsp; // Set the player choices&nbsp; &nbsp; playerChoice = e.target.id;&nbsp; &nbsp; player.style.backgroundImage = 'url(' + bgURLs[playerChoice] + ')';&nbsp; &nbsp;&nbsp; &nbsp; computer.style.backgroundImage = 'url(' + bgURLs[getComputerChoice()] + ')';&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Test the results:&nbsp; &nbsp; console.clear();&nbsp; &nbsp; console.log(playerChoice, computerChoice);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Now update the progress bars&nbsp; &nbsp; compareChoices();&nbsp; }})function compareChoices() {&nbsp; // Use && for logical AND short-circuiting&nbsp; // Ensure that scores don't go below 0 or above 100&nbsp; // Not sure what beats what so you'll have to adjust as needed.&nbsp; if (playerChoice === "Air" && computerChoice === "Fire") {&nbsp; &nbsp; &nbsp;playerHealth = (playerHealth += 25) > 100 ? 100 : playerHealth;&nbsp; &nbsp; &nbsp;computerHealth = (computerHealth -= 25) < 0 ? 0 : computerHealth;&nbsp; } else if (playerChoice === "Air" && computerChoice === "Water") {&nbsp; &nbsp; &nbsp;playerHealth = (playerHealth += 25) > 100 ? 100 : playerHealth;&nbsp; &nbsp; &nbsp;computerHealth = (computerHealth -= 25) < 0 ? 0 : computerHealth;&nbsp; &nbsp; &nbsp;&nbsp; } else if (playerChoice === "Fire" && computerChoice === "Air") {&nbsp; &nbsp; &nbsp;playerHealth = (playerHealth -= 25) < 0 ? 0 : playerHealth;&nbsp; &nbsp; &nbsp;computerHealth = (computerHealth += 25) > 100 ? 100 : computerHealth;&nbsp; &nbsp; &nbsp;&nbsp; } else if (playerChoice === "Fire" && computerChoice === "Water") {&nbsp; &nbsp; &nbsp;playerHealth = (playerHealth -= 25) < 0 ? 0 : playerHealth;&nbsp; &nbsp; &nbsp;computerHealth = (computerHealth += 25) > 100 ? 100 : computerHealth;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; } else if (playerChoice === "Water" && computerChoice === "Air") {&nbsp; &nbsp; &nbsp;playerHealth = (playerHealth -= 25) < 0 ? 0 : playerHealth;&nbsp; &nbsp; &nbsp;computerHealth = (computerHealth += 25) > 100 ? 100 : computerHealth;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; } else if (playerChoice === "Water" && computerChoice === "Fire") {&nbsp; &nbsp; &nbsp;playerHealth = (playerHealth += 25) > 100 ? 100 : playerHealth;&nbsp; &nbsp; &nbsp;computerHealth = (computerHealth -= 25) < 0 ? 0 : computerHealth;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; }&nbsp;&nbsp; // You must update the progress bars from within the function&nbsp; // that changes their values.&nbsp; playerProg.value = playerHealth;&nbsp; computerProg.value = computerHealth;}#Player, #Computer {&nbsp;&nbsp; width:100px;&nbsp; height:50px;&nbsp; background-size:contain;&nbsp; background-repeat:no-repeat;&nbsp; margin:5px 0;}.element { cursor:pointer; display:inline; font-weight:bold; }#Play-Area { clear:both; }#Play-Area div { display:inline-block; }#PlayerBar, #ComputerBar {&nbsp; margin:10px 10px; float:left;}<p>Choose Your Element</p><div id="Options" >&nbsp; <div id="Air" class="element">Air</div>&nbsp; <div id="Fire" class="element">Fire</div>&nbsp; <div id="Water" class="element">Water</div></div><div id="PlayerBar">&nbsp; <div>Player Health</div>&nbsp; <progress id="player-health" value="100" max="100"></progress></div><div id="ComputerBar">&nbsp;<div>Computer Health</div>&nbsp;<progress id="computer-health" value="100" max="100"></progress></div><div id="Play-Area">&nbsp; <div id="Player"></div>&nbsp; <div id="Computer"></div></div>

沧海一幻觉

我不久前就这样做了,并显示了不同的栏,基本上就是您的目标。计算在那里,并且条形图以不同的颜色显示(内联 CSS)。function myMax() {document.myform.num1.value=document.myform.number1.value;document.myform.num3.value=document.myform.number2.value;document.myform.num2.value=document.myform.number3.value;document.myform.num4.value=document.myform.number4.value;document.myform.max1y2.value=Math.max(document.myform.num1.value,document.myform.num2.value);document.myform.max3y4.value=Math.max(document.myform.num3.value,document.myform.num4.value);document.myform.maxAll.value=Math.max(document.myform.max1y2.value,document.myform.max3y4.value);if(isNaN(document.myform.maxAll.value)){alert("Error in page, Probably Not A Number in a Value");return false;}elsedocument.myform.pct1.value=Math.floor((document.myform.num1.value / document.myform.maxAll.value) * 100);document.getElementById("bar1").style.width = document.myform.pct1.value+'%';document.myform.pct2.value=Math.floor((document.myform.num2.value / document.myform.maxAll.value) * 100);document.getElementById("bar2").style.width = document.myform.pct2.value+'%';document.myform.pct3.value=Math.floor((document.myform.num3.value / document.myform.maxAll.value) * 100);document.getElementById("bar3").style.width = document.myform.pct3.value+'%';document.myform.pct4.value=Math.floor((document.myform.num4.value / document.myform.maxAll.value) * 100);document.getElementById("bar4").style.width = document.myform.pct4.value+'%';}function checkIt(evt) {&nbsp; &nbsp; evt = (evt) ? evt : window.event&nbsp; &nbsp; var charCode = (evt.which) ? evt.which : evt.keyCode&nbsp; &nbsp; if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 46 || charCode > 46 )) {//set for 46 dot. For dash = (charCode < 45 || charCode > 45 )&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; status = "This field accepts numbers only."&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }&nbsp; &nbsp; status = ""&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; return true}<hr style="position:relative;top: -28px;border: 4px solid black;">&nbsp;<h3 style="width: 50%;background-color:navy;color:white;position:relative;top: -28px;">&nbsp;VALUES:</h3><b style="position:relative;top: -38px;">Please fill only 3 Values out of 4:</b><form align="left" name="myform" style="position:relative;top: -40px;"><br><table align="left" border="1" cellpadding="4" cellspacing="0" width="34%">&nbsp;<tbody>&nbsp;<tr><th>[Column A]</th>&nbsp;</tr><tr>&nbsp; &nbsp; <!-- Column 1 Row 1 -->&nbsp; &nbsp; <td><div align="left"><font color="olive"> Value 1 <input name="number1" size="8" maxlength="" tabindex="1" onblur="myMax()" onkeypress="return checkIt(event)" autofocus="" type="tel"><input name="unitA" size="4" value="Unit A" readonly="readonly" type="text"></font></div><font color="olive">&nbsp; &nbsp; </font></td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <!-- Column 1 Row 2&nbsp; -->&nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<div align="left"><font color="orange">Value 3 </font><input name="number2" size="8" maxlength="" tabindex="3" onblur="myMax()" onkeypress="return checkIt(event)" type="tel"><input name="unitA" size="4" value="Unit A" readonly="readonly" type="text"><input title="Clear Value 3" type="button" onclick="document.myform.number2.value='';document.myform.number2.focus();return false" value="X">&nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp; </td>&nbsp; </tr></tbody></table><table align="left" border="0" cellpadding="4" cellspacing="0" height="67" width="5%">&nbsp; <tbody>&nbsp; <tr>&nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp;<div style="font-family:arial;font-weight:bold" align="center"><br><br> =</div>&nbsp; &nbsp;</td>&nbsp; </tr>&nbsp; &nbsp;</tbody></table><table border="1" cellpadding="4" cellspacing="0" width="34%">&nbsp; <tbody>&nbsp; &nbsp; &nbsp;<tr><th>[Column B]</th>&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;</tr><tr>&nbsp; &nbsp; <!-- Column 2 Row 1 -->&nbsp; &nbsp; <td>&nbsp; &nbsp;<div align="left"><font color="green">Value 2 </font> <input name="number3" size="8" maxlength="" tabindex="2" onblur="myMax()" onkeypress="return checkIt(event)" type="tel">&nbsp;<input name="unitB" size="4" value="Unit B" readonly="readonly" type="text">&nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp; </td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <!-- Column 2 Row 2 -->&nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<div align="left"><font color="red">Value 4 <input name="number4" size="8" maxlength="" tabindex="4" onblur="num4.value=this.value;myMax()" onkeypress="return checkIt(event)" type="tel"><input name="unitB" size="4" value="Unit B" readonly="readonly" type="text"><input title="Clear Value 4" type="button" onclick="document.myform.number4.value='';document.myform.number4.focus();return false" value="X"></font></div><font color="red"></font></td>&nbsp; </tr></tbody></table><font color=olive>Value 1 </font><input name=num1 maxlength="" type="text" readonly><input name=pct1 maxlength="" size="4" type="text" readonly>%<div style="position:relative;top: -4px; text-align:none;"><div style="height: 20px; width: 100%; background-color: #ddd;"><div id=bar1 style="height: 20px; background-color: olive; width: 0%;" align="left" ></div></div><font color=green>Value 2 </font><input name=num2 maxlength="" type="text" readonly><input name=pct2 maxlength="" size="4" type="text" readonly>%<div style="position:relative;top: -4px; height: 20px; width: 100%; background-color: #ddd;"><div id=bar2 style="height: 20px; background-color: green; width: 0%;" align="left" ></div><!-- Ruler --><div style="z-index:50;position: relative;height: 18px; border-top: 2px dashed silver; width: 100%;">0%</div><center style="z-index:20;position:relative;top: -20px;"> 50% </center><div style="z-index:20;position:relative;top: -38px; text-align:right;">100%</div><!-- /Ruler --></div></div><div style="position:relative;top: 8px; text-align:none;">Max from 1&2 = <input name=max1y2 maxlength="" type="text" readonly></div><br><br><font color=orange>Value 3 </font><input name=num3 maxlength="" type="text" readonly><input name=pct3 maxlength="" size="4" type="text" readonly>%<div style="position:relative;top: -4px; text-align:none;"><div style="height: 20px; width: 100%; background-color: #ddd;"><div id=bar3 style="height: 20px; background-color: orange; width: 0%;" align="left" ></div></div><font color=red>Value 4 </font><input name=num4 maxlength="" type="text" readonly><input name=pct4 maxlength="" size="4" type="text" readonly>%<div style="position:relative;top: -4px; height: 20px; width: 100%; background-color: #ddd;"><div id=bar4 style="height: 20px; background-color: red; width: 0%;" align="left" ></div><!-- Ruler --><div style="z-index:50;position: relative;height: 18px; border-top: 2px dashed silver; width: 100%;">0%</div><center style="z-index:20;position:relative;top: -20px;"> 50% </center><div style="z-index:20;position:relative;top: -38px; text-align:right;">100%</div><!-- /Ruler --></div></div><div style="position:relative;top: 8px; text-align:none;">Max from 3&4 = <input name=max3y4 maxlength="" type="text" readonly><br>Max from All <input name=maxAll maxlength="" type="text" readonly></div><br>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5