如何比较JavaScript中的颜色? [英] How to compare colors in JavaScript?

查看:98
本文介绍了如何比较JavaScript中的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这行不通?即使颜色 等于#ECECF4,它仍然会警告否". 正如我测试过的那样,它正在选择corrent元素.有没有更好的方法来写这个?

<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输出十六进制值,IE9和更高版本以及其他浏览器输出RGB格式.因此,将颜色与跨浏览器的兼容性进行比较是一项艰巨的任务,做到这一点的最佳方法并不美观. >

我做了一个简单的功能,即使在通过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函数,将元素本身作为回调的上下文传递,从而可以轻松地通过this访问元素.

可以扩展为在使用HSLA或RGBA时将alpha纳入考虑范围.


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

Why doesn't this work? Even though the colour is equal to #ECECF4 it still alerts "No". It is selecting the corrent element as I have tested it. Is there a better way to write this?

<script type="text/javascript">

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

</script>

解决方案

Comparing colors as part of the business logic should be avoided at all cost.

Instead, keep the logic in JavaScript and act according to a state kept somewhere. Then, if you want to send a visual feedback to the user through a change of color, add a class to the element. That way, JavaScript only knows about class names and the styling is always isolated in the CSS as it should.

$(".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>


That being said, OP's code works for me with Chrome 17.0.963.56 and Firefox 8.0. When you don't know what to compare, just use console.log() to see what it looks like.

Note that #ECECF4 is the same color as rgb(236, 236, 244) but in a different representation.

IE7 and IE8 output the HEX value, IE9 and up and other browsers output the RGB format. So comparing color with cross-browser compatibility is a tricky task and the best way to do it isn't beautiful.

I made a simple function which works for most cases with most browser, even with color set through 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>

I call the weekclick function with javascript:weekclick.call(this) passing the element itself as the context of the callback, making it easy to access the element with this.

It could be extended to take alpha into account when using HSLA or RGBA.


When I originally wrote this answer back in 2012, I used navigator.appName === "Microsoft Internet Explorer" to know if it was IE7 and the color to compare was changed to its HEX equivalent. Don't do that as it won't work today.

这篇关于如何比较JavaScript中的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆