javascript - 如何在 JavaScript 中比较颜色?

标签 javascript html css

为什么这行不通?即使颜色 等于 #ECECF4,它仍然会提示“No”。 它正在选择我测试过的正确元素。有没有更好的写法?

<script type="text/javascript">

function weekclick() {
    if (document.getElementById('w1').style.backgroundColor == "#ECECF4") {
        alert("Yes");
    } else {
        alert("No");
    }
}

</script>

最佳答案

应不惜一切代价避免将颜色比较作为业务逻辑的一部分。

相反,将逻辑保留在 JavaScript 中并根据保存在某处的状态进行操作。然后,如果您想通过颜色的变化向用户发送视觉反馈,请向该元素添加一个类。这样,JavaScript 只知道类名,而样式始终在 CSS 中隔离,这是它应该做的。

$(".list").on("click", "li", function(){
    $(this).toggleClass('active');
});
.list {
  width: 100%;
  padding: 0;
}
.list li {
  padding: 5px 10px;
  list-style: none;
  cursor: pointer;
}
.list li:hover {
  background-color: rgba(0, 0, 0, 0.05);
}
.list li.active {
  background-color: #eeeecc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
  <li>test 1</li>
  <li>test 2</li>
  <li>test 3</li>
</ul>


也就是说,OP 的代码适用于 Chrome 17.0.963.56 和 Firefox 8.0。当您不知道要比较什么时,只需使用 console.log() 看看它是什么样子。

请注意,#ECECF4rgb(236, 236, 244) 颜色相同,但表示形式不同。

IE7、IE8输出HEX值,IE9及以上及其他浏览器输出RGB格式。因此,将颜色与跨浏览器兼容性进行比较是一项棘手的任务,而且 best way to do it isn't beautiful .

我做了一个简单的函数,它适用于大多数浏览器的大多数情况,即使通过 CSS 设置颜色也是如此。

function weekclick() {
    var elemColor = getStyle(this, "backgroundColor"),
        color = "rgb(238, 238, 204)";

    console.log("Broswer returned elem color: ", elemColor);

    // IE7 and IE8 output the hex value
    if (elemColor.slice(0, 1) === '#') elemColor = hexToRgb(elemColor);

    console.log(elemColor, " === ", color, "?", elemColor === color);
}

// Source: https://stackoverflow.com/a/41354868/1218980
// Inspired by: https://stackoverflow.com/a/22744598/1218980
function getStyle(el, prop) {
    return (typeof getComputedStyle !== 'undefined' ?
        getComputedStyle(el, null) :
        el.currentStyle
    )[prop];
}


// Slightly modified version to quickly return a string
// https://stackoverflow.com/a/5624139/1218980
function hexToRgb(hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? "rgb(" + [
        parseInt(result[1], 16),
        parseInt(result[2], 16),
        parseInt(result[3], 16)
    ].join(', ') + ")" : null;
}
#css-div {
  background-color: #eeeecc;
}
<div style="Background-color:#eeeecc" onclick="javascript:weekclick.call(this);">#eeeecc</div>
<div style="Background-color:#EEC" onclick="javascript:weekclick.call(this);">#EEC</div>
<div style="background-color:hsla(60, 50%, 86.7%, 1)" onclick="javascript:weekclick.call(this);">hsla(60, 50%, 86.7%, 1)</div>
<div style="background-color:rgb(238, 238, 204)" onclick="javascript:weekclick.call(this);">rgb(238, 238, 204)</div>
<div id="css-div" onclick="javascript:weekclick.call(this);">css</div>

我使用 javascript:weekclick.call(this) 调用 weekclick 函数,将元素本身作为回调的上下文传递,从而可以轻松访问元素这个

它可以扩展为在使用 HSLA 或 RGBA 时考虑 alpha。


当我最初在 2012 年写这个答案时,我使用 navigator.appName === "Microsoft Internet Explorer" 来知道它是否是 IE7 并且要比较的颜色更改为它的十六进制等价物。不要那样做,因为它今天行不通。

关于javascript - 如何在 JavaScript 中比较颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9421208/

相关文章:

HTML 页面 - 页眉和页脚 - 冗余

html - CSS 多浏览器中的 Aqua 按钮

html - 图像不在中间

javascript - 如何仅使用 jsdoc 在 webstorm 中记录类型?

javascript - React Native 添加到状态数组

javascript - 按钮可拖动,同时内容可编辑

html - 如何只缩放外部 div 而不是内部 div

javascript - 在本地磁盘上的父 HTML iframe 的 javascript postmessage

javascript - 当我单击另一个音频播放器时如何停止播放一个音频播放器 - javascript

jquery - 切换 float 菜单应该使内容更流畅