How to stop Javascript code from automatically converting hsl to rgb
P粉806834059
P粉806834059 2024-03-31 16:46:02
0
1
476

I have this code where I assign a color to an object and then use a condition to check if the item has been selected. However, the condition doesn't work because javascript (or the browser) converts hsl to rgb, which prevents any matching from happening. I'm wondering if there is a way to prevent this behavior in JS (or browsers), and if not, why does it happen?

function selecionarNota() {

    if (this.style.backgroundColor == 'hsl(25, 97%, 53%)') { 
        for (let i = 0; i < numAvaliacao.length; i++) {
            numAvaliacao[i].style.backgroundColor = 'hsl(213, 19%, 21%)';
            numAvaliacao[i].style.color = 'hsl(217, 12%, 63%)';
        }

    } else {

        for (let i = 0; i < numAvaliacao.length; i++) {
            numAvaliacao[i].style.backgroundColor = 'hsl(213, 19%, 21%)';
            numAvaliacao[i].style.color = 'hsl(217, 12%, 63%)';
        }

        this.style.backgroundColor = 'hsl(25, 97%, 53%)';
        this.style.color = 'white';

    }
}

I did realize that I could solve this problem by using rgb in my code. But I'd really like to understand why this happens.

P粉806834059
P粉806834059

reply all(1)
P粉076987386

This happens because it is a browser standard.

I recommend creating css classes with these colors and applying these classes in javascript. You can then use element.classList.contains(class) in your condition.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template