javascript - 具有 RGBA 背景颜色的 IF 条件

标签 javascript css rgba

如何在纯 JavaScript 中编写一个 IF 条件来检查 <li> 的背景颜色是否存在标签等于特定的 RGBA 颜色组合。

例如:

if(document.getElementById('element').style.backgroundColor == "rgba(213,212,212,0.5)")
{
     alert("MATCHED");
}
else
{
     alert("FAILED");
}

但是 IF 语句的这种比较有效!请帮忙!

最佳答案

CSS 值以特定方式返回。

尝试将其与:"rgba(213, 212, 212, 0.5)"

(每个逗号后有空格)。

由于 JavaScript 的舍入误差是最严重的,而且你真的不关心 alpha,所以你可以删掉你需要的部分:

var color = document.getElementById('element').style.backgroundColor;
color = color.substring(
                          color.indexOf('(') + 1,
                          color.lastIndexOf(color[3] == 'a' ? ',' : ')')
                        );

if (color == '213, 212, 212')
{
    alert("MATCHED");
}
else
{
    alert("FAILED");
}

无论是 rgb 还是 rgba 都有效

如果 background-color 未定义为内联样式,您可能需要使用:

var color = window.getComputedStyle(document.getElementById('element')).backgroundColor;

代替(代码中的第一行)。

关于javascript - 具有 RGBA 背景颜色的 IF 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23188686/

相关文章:

javascript - 多米诺 Angular 通用 : Getting Right-hand side of 'instanceof' is not an object

javascript - 如何提交表单然后重定向到个性化感谢页面?

html - 在不影响页面样式的情况下,在页面中嵌入带有 css 的 html 字符串

html - 我无法让我的页眉图片适合页面内容

html - Internet Explorer 中的 CSS rgba

asp.net - 按钮禁用..但是

javascript - Angular- Jasmine : Unknown provider: $modalProvider <- $modal

css - 为什么更改 CSS 类名会破坏样式?

jquery - 通过 jquery 获取 rgba 背景颜色

c++ - 使用 C++ 和 RGBA 像素 vector 的双线性调整大小