javascript - 单击时切换按钮背景颜色

标签 javascript html css

我有这个功能,旨在每次单击按钮时在按钮的两种预定义颜色之间切换背景:

const showAvailButtonClicked = (targetButton, clickedColor, unClickedColor) => {
  let clickedElement = document.getElementById(targetButton)
  let currColor = clickedElement.style.backgroundColor
  if (currColor == clickedColor) {
    clickedElement.style.backgroundColor = unClickedColor
  } else {
    alert("Current color:" + currColor)
    clickedElement.style.backgroundColor = clickedColor
  }
}

let targetButton = document.getElementById("testbutton")
targetButton.addEventListener("click", () => {
  showAvailButtonClicked("testbutton","#ba0202", "#0f2e0c")
})
#testbutton {
  background-color: #0f2e0c;
}
<button id="testbutton">Toggle</button>

我在上面这段简单的代码中遇到了两个问题:

1 - 按钮以这种颜色 unClickedColor = #0f2e0c 开始。但是,在第一次单击时,警报不会注册任何颜色。 IE。警报消息仅显示 Current color:

2 - 在第 2 次和后续点击时,此行 let currColor = clickedElement.style.backgroundColor 的注册颜色给出 RGB 格式 rgb(r, g, b)。我如何强制它变成十六进制格式以便我可以进行颜色比较?谢谢。

最佳答案

更好的做法是将一个类附加到单击按钮上并在该类上设置样式。

以下代码段为按钮设置了基本背景颜色,然后在单击它时 - 切换“已单击”类 - 在应用时 - 提供备用背景颜色。

这实现起来更简单,因为您不必确定现有的背景颜色,然后再进行一些时髦的十六进制比较,而且最好将 html、js 和 css 分开到它们自己的领域中。

let testButton = document.getElementById("testbutton");

testButton.addEventListener("click", () => {
  testButton.classList.toggle('clicked');
})
#testbutton {
  background-color: #0f2e0c;
  color: white
}

#testbutton.clicked {
  background-color: #ba0202;
}
<button id="testbutton">Toggle</button>

关于javascript - 单击时切换按钮背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65350502/

相关文章:

javascript - Titanium android 中的内存管理

javascript - 将内容放入带有图标的列中

javascript - scrollspy 导航到不同的页面并返回同一位置

css - 为什么不使用 ckeditor 在文本区域中包含元素的样式?

html - CSS 样式表加载错误

html - 如何在html中的同一行上有两个标题

javascript - 当在 "TypeError: Cannot read property ' 内部时, react "Map"未定义状态'

javascript - 获取html页面中的所有段落id

html - 当您更改背景颜色时,SVG 未正确填充显示

html - 恢复 Wordpress 样式表