简体   繁体   中英

How to do Javascript Function which will change the style display of element?

function burgerMenu(){
            //alert(document.getElementById("hiddenMenuUL").style.display);
            if(document.getElementById("hiddenMenuUL").style.display="none"){
                document.getElementById("hiddenMenuUL").style.display="block";
            }
            else if(document.getElementById("hiddenMenuUL").style.display="block"){
                document.getElementById("hiddenMenuUL").style.display="none";
            }
    }

I want to toggle the burger menu icon. So if I press the icon the burgerMenu() function will be toggle and verify if its display: none then change to display:block and vice versa. hiddenMenuUL is the for list of links. This line below is the button line in HTML:

<button class="btn" onclick="burgerMenu()">&#9776;</button>

My CSS for hiddenMenuUL

#hiddenMenuUL{
        display: none;
        list-style: none;
        width: 100%;
        justify-content: center;
    }

When you are writing your if, you are not actually checking if the display === "none", you are trying to set it to none.

What you should be doing looks like this:

function burgerMenu(){
            let menuStyle = document.getElementById("hiddenMenuUL").style.display;
            if(menuStyle === 'none'){
                document.getElementById("hiddenMenuUL").style.display="block";
            }
            else {
                document.getElementById("hiddenMenuUL").style.display="none";
            }
    }

Edit:

It seems display rule is defined in CSS, and isn't inline.

.style can only reach inline styles, for example:

<div id="hiddenMenuUL" style="display: none;"></div>

Adding 'display: none' inline like in the example above should be the fastest and easiest way to 'fix' it in your particular scenario, although it probably wouldn't be considered the best practice.

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