如何在javascript中知道按钮的背景颜色?

时间:2018-11-25 06:57:28

标签: javascript html

我有一个黄色按钮。

当我单击按钮时,我想获取按钮的颜色。

我尝试过:

<html>

<head>
  <style rel="stylesheet">
    .A {
      background-color: #ffff00
    }
  </style>
  <script>
    function clicked() {
      console.log(document.getElementById("A1").style.backgroundColor);
    }
  </script>
</head>

<body>
  <input type="button" id="A1" class="A" value="1" onclick="clicked()">
</body>

</html>

那我什么也没得到。

如何获得“黄色”或“#ffff00”?

3 个答案:

答案 0 :(得分:3)

您可以尝试使用$loop->addTimer()方法来获取按钮样式:

getComputedStyle
function clicked() {
  var button = document.getElementById("A1");
  var style = getComputedStyle(button);
  
  console.log(style['background-color']);
}
.A { background-color: #ffff00 }

答案 1 :(得分:0)

您的CSS

<style rel="stylesheet">
    .A { background-color: #ffff00 }
</style>

您必须以这种方式编写

<input type="button" id="A1" class="A" value="1" onclick="clicked()">

    <script>
    function clicked() {
    const element = document.getElementById('A1');
    const style = getComputedStyle(element);
        console.log(style.backgroundColor);
    }
</script>

答案 2 :(得分:0)

您必须使用window.getComputedStyle()

  

window.getComputedStyle()方法返回一个对象,该对象在应用活动样式表并解决这些值可能包含的所有基本计算之后,报告元素的所有CSS属性的值。可以通过对象提供的API或通过简单地使用CSS属性名称进行索引来访问各个CSS属性值。

然后,您必须将 rgb 值转换为 hex

您可以尝试以下方式:

function clicked(el) {
  var bg_color = window.getComputedStyle(el, null).backgroundColor;
  bg_color = bg_color.match(/\d+/g);
  console.log(rgbToHex(bg_color));
}
    
function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(rgb) {
  return "#" + componentToHex(+rgb[0]) + componentToHex(+rgb[1]) + componentToHex(+rgb[2]);
}
.A { background-color: #ffff00 }
<input type="button" id="A1" class="A" value="1" onclick="clicked(this)">