【问题标题】:Toggle button background color when clicked单击时切换按钮背景颜色
【发布时间】:2021-03-28 17:19:28
【问题描述】:

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

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 来重现您的问题。
  • 嗨,我已经更新了问题。

标签: javascript html css


【解决方案1】:
  1. 您需要使用window.getComputedStyle(clickedElement).backgroundColorstyle 属性仅包含在样式属性中分配或由脚本设置的样式。您也可以改用以下内容:
const currColor = window.getComputedStyle ? window.getComputedStyle(clickedElement, null).getPropertyValue("background-color") : clickedElement.style.backgroundColor;
  1. 默认浏览器会给你rgb值。您需要手动将其转换为十六进制。我为此目的使用了这个函数。
function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

const showAvailButtonClicked = (targetButton, clickedColor, unClickedColor) => {
  let clickedElement = document.getElementById(targetButton);

  let currColor = rgb2hex(window.getComputedStyle(clickedElement).backgroundColor);

  alert("Current color:" + currColor);
  
  if (currColor == clickedColor) {
    clickedElement.style.backgroundColor = unClickedColor
  } else {
    clickedElement.style.backgroundColor = clickedColor
  }
}

let targetButton = document.getElementById("testbutton")

targetButton.addEventListener("click", () => {
  showAvailButtonClicked("testbutton","#ba0202", "#0f2e0c")
})
#testbutton {
  background-color: #0f2e0c;
  color: #fff;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <button id="testbutton">Toggle</button>

</body>
</html>

【讨论】:

  • 感谢您解释window.getComputedStyle 部分和代码以及第一个回复。我将使用@gavgrif 的解决方案,因为它看起来更通用。我可以避免处理 RGB 转换。
  • function rgb2Hex(r,g,b){ return '#' + ((r&lt;&lt;16) + (g&lt;&lt;8) + b).toString(16);} 一直为我服务。 :)
【解决方案2】:

最好将一个类附加到单击按钮上并在该类上设置样式。

以下 sn-p 为按钮设置了基本背景颜色,然后当它被点击时 - 切换“点击”类 - 当应用时 - 提供替代背景颜色。

这更容易实现,因为您不必确定现有的背景颜色,然后进行一些时髦的十六进制比较,而且将 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;
}
&lt;button id="testbutton"&gt;Toggle&lt;/button&gt;

【讨论】:

    【解决方案3】:

    使用getComputedStyle并保持RGB,没有理由不能使用。 Alos 使用 data 属性存储各种按钮的替代颜色,然后存储原始颜色。

    document.querySelectorAll(".toggle").forEach(function(el) {
      //Don't use arrow function we want acces to "this"
      el.addEventListener("click", function() {
        //grab the computed style
        let style = getComputedStyle(this);
        //Note color will be RGB
        console.log("Current color: " + style.backgroundColor);
        //Store current color
        let tempStyle = style.backgroundColor;
        //swap the color
        this.style.backgroundColor = this.dataset.altcolor;
        //store the previous color
        this.dataset.altcolor = tempStyle;
      });
    });
    .toggle {
      background-color: #0f2e0c;
    }
    
    .toggle.alt {
      background-color: #0000FF;
    }
    <button class="toggle" data-altcolor="#ba0202">Toggle</button>
    <button class="toggle" data-altcolor="#ff0000">Toggle</button>
    <button class="toggle alt" data-altcolor="#00ff00">Toggle</button>

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 2013-06-07
      • 1970-01-01
      • 2014-10-09
      • 2017-08-02
      • 2017-08-19
      • 1970-01-01
      • 2017-01-26
      • 2014-10-10
      相关资源
      最近更新 更多