简体   繁体   中英

javascript toggle menu bar

I have an html menu with a button to open it and a unordered list:

 <nav class="menu">
        <button>
            <h1>Menu</h1>
        </button>

        <ul class="mylist">
            <li>About</li>
            <li>Contact</li>
            <li>Services</li>
        </ul>
        
    </nav>

I want to use javascript to alter the ul class to change its margin on click: CSS:

.mylist{
    margin: 300em;
}

.mylist.shown{
    margin: 2em;
}

This script doesn't function, can someone point out my problem, thank you

let hiddenList= document.querySelector('.mylist');
let button= document.querySelector('button');
hiddenList.style.margin= '300em';



button.addEventListener('click', function(){
    hiddenList.classList.toggle('shown')
})

You don't need to set margin with the line:

hiddenList.style.margin= '300em';

since you already define the element with that margin in the CSS with:

.mylist{
    margin: 300em;
}

So just remove that.

The reason that was causing a problem is that the line of script was the equivalent of adding the following to the HTML:

<ul class="mylist" style="margin: 300em">

And with the rules of precedence in CSS being what they are, that inline style has a higher priority over that declared in the CSS.

See MDN's article on CSS Specificity for more details.

Your problem is you fixed inline style by this line:

hiddenList.style.margin= '300em';

Then just remove it then everything works

 let hiddenList= document.querySelector('.mylist'); let button= document.querySelector('button'); button.addEventListener('click', function(){ console.log(hiddenList) hiddenList.classList.toggle('shown') })
 .mylist{ margin: 300em; }.mylist.shown{ margin: 2em; }
 <nav class="menu"> <button> <h1>Menu</h1> </button> <ul class="mylist"> <li>About</li> <li>Contact</li> <li>Services</li> </ul> </nav>

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