javascript - 实时条件背景变化

标签 javascript dom

我正在制作一个 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/

相关文章:

javascript - 是否存在反向查询选择器?

javascript - 将 Angular 元素绑定(bind)到 Controller 外部的范围

javascript - 删除字符串末尾的特定字符(html 元素)

javascript - 为什么 Webkit 不能正确重绘我的网页?

Javascript:如何为所有其他对象集中一个对象?

javascript - 如何在函数中正确访问 DOM?

Java getElmentsByTagName 与通配符

javascript - Firefox 可以调节计算机上的麦克风音量,但 Chrome 不行

javascript - 在 Javascript 中基于滚动显示/隐藏图像

javascript - 观察插入的元素及其以编程方式更新的值