我正在制作一个 ATM 应用程序作为一个学校项目,基本上,支票和储蓄账户的背景颜色会根据当前余额而变化。问题是虽然它变为红色(因为帐户默认为 0),但它不会变为黄色(50 美元)或绿色(100 美元)
currentBalance 是全局的,用来保留数据。它从那里拉那个变量。 “ID”特定于支票或储蓄账户。我可以确认颜色变化有效,因为它从绿色(默认)变为红色,但一旦余额开始实时更新,它就不会改变。
var currentBalance = 0
function depositMoney(id) {
// Select deposit button and add functionality
document.querySelector(`${id} .deposit`).addEventListener("click", function(event) {
// Prevent refresh page default
event.preventDefault()
// Obtain data from input box
let deposited = document.querySelector(`${id} .input`).value
// Turn data (currently string) into a number
let intDeposited = parseInt(deposited)
// Add number to current balance
currentBalance += intDeposited
// Select balance div which is where the balance will be shown
let balanceNumber = document.querySelector(`${id} .balance`)
// Show changed balance by modifying innerHTML and turning current balance into a string
balanceNumber.innerHTML = "$" + currentBalance.toString();
})
}
function backgroundColorBalance(id) {
let accountColor = document.querySelector(`${id}`)
if (currentBalance <= 25 && currentBalance >= 0) {
accountColor.style.backgroundColor = "red"
}
if (currentBalance <= 50 && currentBalance > 25) {
accountColor.style.backgroundColor = "yellow"
}
if (currentBalance > 50) {
accountColor.style.backgroundColor = "green"
}
}
// Invoke depositMoney() function for checking account
depositMoney("#checking")
// Invoke backgroundColorBalance() function for checking account
backgroundColorBalance("#checking")
<div class="header">
<div><img src="ga.png" /></div>
<div class="title">Bank of GA</div>
</div>
<div id="checking" class="account">
<h2>Checking</h2>
<div class="balance">$0</div>
<input class="input" type="text" placeholder="enter an amount" />
<input class="deposit" type="button" value="Deposit" />
<input class="withdraw" type="button" value="Withdraw" />
</div>
<div id="savings" class="account">
<h2>Savings</h2>
<div class="balance">$0</div>
<input class="input" type="text" placeholder="enter an amount" />
<input class="deposit" type="button" value="Deposit" />
<input class="withdraw" type="button" value="Withdraw" />
</div>
最佳答案
您需要在账户余额发生变化后重新设置背景颜色。因此,将以下内容添加到您的事件监听器代码中的最后一行。
backgroundColorBalance(`${id}`);
关于javascript - 实时条件背景变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58188204/