How to compare backgroundColor in javascript?

Why is this not working? Even if the color is #ECECF4 , it still warns no. It selects the corrent element as I 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> 
+4
source share
5 answers

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

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

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

As the saying goes, the OP 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 how it looks.

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

IE7 and IE8 display the value HEX , IE9 and higher, while other browsers display the RGB format. Therefore, comparing color with compatibility between browsers is a difficult task, and the best way to do this is not beautiful .

I made a simple function that works in most cases with most browsers, even with color set via 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 (eg "03F") to full form (eg "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 = /^#?([af\d]{2})([af\d]{2})([af\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 a callback context, making it easier to access the element with this .

It can be expanded to accept alpha when using HSLA or RGBA.


When I originally wrote this answer back in 2012, I used navigator.appName === "Microsoft Internet Explorer" to find out if it was IE7, and the comparison color was changed to its HEX equivalent. Do not do this as it will not work today.

+8
source

I'm actually just learning javascript, but instead of creating a function that converts rgb () to hex, you can create a div of the same background color you are looking for and compare it with the background color of the div. If you already have a div for this hex value, you can simply do this:

 //javascript if (document.getElementId('desiredElementToCompare').style.backgroundColor === document.getElementId('elementWithTheDesiredHexString').style.backgroundColor) //jQuery if ($('#desiredElementToCompare').css('background-color') === $('#elementWithTheDesiredHexString').css('background-color') 

You can create a div with a function and then perform the comparison as follows:

 var compareHex = (hex) => { var hexString = document.createElement('div') hexString.style.backgroundColor = `${hex}` return hexString.style.backgroundColor } //then compare //javascript if (document.getElementId('desiredElementToCompare').style.backgroundColor === compareHex("#ECECF4")) //jQuery if($('#desiredElementToCompare').css('background-color') === compareHex("#ECECF4") 
+2
source

I would advise using '===' stric equal (I think this is the name).

how

 if (document.getElementById('test').style.backgroundColor === "rgb(236, 236, 244)") { 
+1
source

This method involves using jQuery background-color , which standardizes the response to rgb(r, g, b) .

How to get background color of an element using javascript?

+1
source

Perhaps this answer might help. Convert the color code to hex, and then compare each color / RGB channel (I don't know the word)

fooobar.com/questions/20092 / ...

I think it's better and easier to compare two numbers than two lines

+1
source

Source: https://habr.com/ru/post/1398123/


All Articles