Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

javascript - Responsive menu show and hide on click

I trying to write a responsive menu. It's actually works but I can't get the on clik effect in CSS. For this moment I'm using a hover. How to make that when the screen width is lower than 750px I have to click on menu from pic. number 2 (ul) to show menu from pic. number 3 (li) ? This is a one page site so when I clik on some element from drop down menu it's should hide menu agin (li).

HTML:

<header>
    <nav id="menu">
        <ul>
            <li class="li"><a href="#">WITAJ</a></li>
            <li class="li"><a href="#">O MNIE</a></li>
            <li class="li"><a href="#">DO?WIADCZENIE</a></li>
            <li class="li"><a href="#">CO ROBI??</a></li>
            <li class="li"><a href="#">KONTAKT</a></li>
            <li><a href="#">MOJE PRACE</a></li
        ></ul>
    </nav>
</header>

CSS:

@media screen and (max-width: 750px) {      
    header nav#menu ul:hover > li{
        display:block !important;
    }

    header nav#menu ul li{
        display:none !important;
    }
}

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot achieve a click effect in CSS. It is common to use JavaScript for that. This is an easy jQuery solution:

$(function() {
  var menuVisible = false;
  $('#menuBtn').click(function() {
    if (menuVisible) {
      $('#myMenu').css({'display':'none'});
      menuVisible = false;
      return;
    }
    $('#myMenu').css({'display':'block'});
    menuVisible = true;
  });
  $('#myMenu').click(function() {
    $(this).css({'display':'none'});
    menuVisible = false;
  });
});

It also hides the menu, after the user clicked on an entry.

In CSS, you have to force the menu to be visible or not by using media queries. Here an example: sfplex

This is the HTML structure of this example:

<div id="menuBtn">click me</div>
<nav id="myMenu">
  <ul>
    <li>entry 1</li>
    <li>entry 2</li>
    <li>entry 3</li>
    <li>entry 4</li>
  </ul>
</nav>

See the working example in jsFiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...