简体   繁体   中英

Toggle visibility of menu based on screen width on page reload

I have a <ul> menu with links and want to add some function which toggles the visibility of the menu depending on the screen width (ie it should hide the menu on screens smaller than 767px). I have tried this code, which seems to work when the window is resized. But on page reload, it does not:

 function toggleVisibility(i) { window.innerWidth < 767 && (i.style.display = "none") } 
 <ul onload="toggleVisibility(this)"> <li><a href='link1.html'>Item 1</a></li> <li><a href='link2.html'>Item 2</a></li> <li><a href='link3.html'>Item 3</a></li> <li><a href='link4.html'>Item 4</a></li> <li><a href='link5.html'>Item 5</a></li> </ul> 

How can I make it hide the menu also on page reload?

You would be much better off using CSS media queries for this. An example:

/* any CSS declared inside will only apply when the window width is 766 or less */
@media (max-width: 766px)
{
    ul
    {
        display: none;
    }
}

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