如何比较backgroundColor在Javascript中? [英] How to compare a backgroundColor in Javascript?

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

问题描述

为什么这不工作?即使颜色 等于#ECECF4 ,它仍然提示否。
它正在选择corrent元素,因为我已经测试它。是否有更好的方法来写这个?

 < script type =text / javascript 

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

< / script>


解决方案

适用于我的Chrome 17.0.963.56和Firefox 8.0。当你不知道要比较什么时,只需使用 console.log()看看它是什么样子。



请注意,#ECECF4 == rgb(236,236,244)以及 IE7和IE8输出HEX值,IE9及以上和其他浏览器输出RGB格式。



因此,将颜色与跨浏览器兼容性进行比较是一个棘手的任务,最好的做法是不美丽



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



  function weekclick(){var elemColor = getStyle(this,backgroundColor ),color =rgb(238,238,204); console.log(Broswer returned elem color:,elemColor); // IE7和IE8输出十六进制值if(elemColor.slice(0,1)==='#')elemColor = hexToRgb(elemColor); console.log(elemColor,===,color,?,elemColor === color);} //源:http://stackoverflow.com/a/41354868/1218980//启发:http: //stackoverflow.com/a/22744598/1218980function getStyle(el,prop){return(typeof getComputedStyle!=='undefined'?getComputedStyle(el,null):el.currentStyle)[prop];} //稍微修改版本快速返回字符串// http://stackoverflow.com/a/5624139/1218980函数hexToRgb(hex){//展开速记形式(例如03F)为完整形式(例如0033FF)var shorthandRegex = / ^ #?([af\d])([af\d])([af\d])$ / i; hex = hex.replace(shorthandRegex,function(m,r,g,b){return r + r + g + g + b + b;}); var result = /^#?([-f\d]{2})([-f\d]{2})([-f\d]{2})$/i.exec(hex);返回结果? rgb(+ [parseInt(result [1],16),parseInt(result [2],16),parseInt(result [3],16)]。 }  

 #css-div {background-color:#eeeecc ;}  

 < div style = #eeeecconclick =javascript:weekclick.call(this);>#eeeecc< / div>< div style =Background-color:#EEConclick =javascript:weekclick.call >#EEC< / div>< div style =background-color:hsla(60,50%,86.7%,1)onclick =javascript:weekclick.call(this); 50%,86.7%,1)< / div>< div style =background-color:rgb(238,238,204)onclick =javascript:weekclick.call(this);> rgb ,238,204)< / div>< div id =css-divonclick =javascript:weekclick.call(this);> css< / div>  



我用<$ c $调用 weekclick c> javascript:weekclick.call(this)传递元素本身作为回调的上下文,使它很容易访问 this



使用HSLA或RGBA时,可以扩展为考虑阿尔法。






也就是说,应该不惜一切代价避免将颜色作为业务逻辑的一部分进行比较



而是,保持JavaScript中的逻辑,并根据保存在某处的状态执行操作。然后,如果要通过更改颜色向用户发送视觉反馈,请向该元素添加一个类。这样,JavaScript只知道类名,而且样式总是在CSS中被隔离。



  $(。list)。on(click,li,function(){$(this).toggleClass('active');}) / code> 

  .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;}  pre> 

 < script src =https://ajax.googleapis.com/ajax/libs/jquery /2.1.1/jquery.min.js\">t;/script><ul class =list> < li>测试1< / li> < li>测试2< / li> < li> test 3< / li>< / ul>  



< hr>

当我最初在2012年写这个答案时,我使用 navigator.appName ===Microsoft Internet Explorer知道它是否是IE7,并且要比较的颜色已更改为其HEX等效值。不要这样做,因为它今天不起作用。


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>

解决方案

That 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 == rgb(236, 236, 244) and also that 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: http://stackoverflow.com/a/41354868/1218980
// Inspired by: http://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
// http://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.


That being said, 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>


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.

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

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