简体   繁体   中英

Change property value background color for pseudo-element dinamically

I have burger menu and need to change background-color by click on icon

I have this code in css

:root{
       --pseudo-backgroundcolor: yellow;
    }
    .menu__icon span,
    .menu__icon::before,
    .menu__icon::after{
        background: var(--pseudo-backgroundcolor);

    }

And this in js

const iconMenu = document.querySelector('.menu__icon');
const root = document.querySelector(":root");
let styleRoot = window.getComputedStyle(root)
let valueProp = styleRoot.getPropertyValue("--pseudo-backgroundcolor")
if (iconMenu) {
    const menuBody = document.querySelector('.menu__body');
    iconMenu.addEventListener("click", function (e) {
        document.body.classList.toggle('_lock');
        iconMenu.classList.toggle('_active');
        menuBody.classList.toggle('_active');
        
        switch (valueProp) {
            case 'yellow':
                root.style.setProperty("--pseudo-backgroundcolor", 'white');
                break

            case 'white':
                root.style.setProperty("--pseudo-backgroundcolor", 'yellow');
        }
    })
}

or instead switch this

if (valueProp == 'white') {
    root.style.setProperty("--pseudo-backgroundcolor", 'yellow');
}
if (valueProp == 'yellow') {
    root.style.setProperty("--pseudo-backgroundcolor", 'white');
}

And i can't understand why switch or if/else constructions doesn't work. This function just doesn't see it.

There is whitespace in the valueProp . You may want to .trim() this var before comparing.

let valueProp = styleRoot.getPropertyValue("--pseudo-backgroundcolor").trim()

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