简体   繁体   中英

Can I compare two RGB colors in Javascript? And how?

I try something like this:

if(elem.css.fill==='rgb(255,255,255)')

but it doesn't work.

You can use getComputedStyle() to get the list of possible css properties and then look for the value of fill style to match with the expected rgb() value.

 let elem = document.querySelector('span'); let style = getComputedStyle(elem); if (style.fill === 'rgb(255, 255, 255)') { console.log('matched!'); }
 .circle { fill: rgb(255,255,255); }
 <span class="circle">Circle</span>

Note that there is a spacing issue while you compare the rgb() values, where rgb(255,255,255) and rgb(255, 255, 255) is considered as different when you compare it as a string value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM