且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义jQuery下拉菜单

更新时间:2022-12-11 17:30:22

你应该使用这样的HTML:

 < div id =#menu> 
< ul>
< li>
< a href =#> Menu1< / a>
< ul>
< li>< a href =#>子菜单A< / a>< / li>
< li>< a href =#>子菜单B< / a>< / li>
< li>< a href =#>子菜单C< / a>< / li>
< / ul>
< / li>
< li>
< a href =#> Menu2< / a>
< ul>
< li>< a href =#>子菜单D< / a>< / li>
< li>< a href =#>子菜单E< / a>< / li>
< li>< a href =#>子菜单F< / a>< / li>
< / ul>
< / li>
< / ul>
< / div>

然后jQuery这样:



$(#menu li)。hover(function(){
$(this).find(ul)。show(fast);
} ,function(){
$(this).find(ul)。hide(fast);
});

然后当您将鼠标悬停在子菜单上时,实际上仍然将鼠标悬停在主菜单上,然后不会关闭。
上面的例子也是灵活的,所以你不需要为每个菜单写一次。


I am creating a custom simple dropdown using jQuery that hides/shows a element based on over state.

The problem I have now is that when you go over the shown element it hides, you cant move your mouse in to the dropdown that was created.

Any thoughts on how to fix that also, is there an easier way to do what I have? I am going to be reusing this and not sure the best way to set the code up for I dont need to copy/paste six times.

$(function(){
    $("#dog-nav").hover(
      function(){
        $(".sub-drop-box-dog").show("fast");
      }, 
      function(){
        $(".sub-drop-box-dog").hide("fast");
      }
    );
    $("#cat-nav").hover(
      function(){
        $(".sub-drop-box-cat").show("fast");
      }, 
      function(){
        $(".sub-drop-box-cat").hide("fast");
      }
    );

});

You should use HTML like this:

<div id="#menu">
  <ul>
    <li>
      <a href="#">Menu1</a>
      <ul>
        <li><a href="#">Submenu A</a></li>
        <li><a href="#">Submenu B</a></li>
        <li><a href="#">Submenu C</a></li>
      </ul>
    </li>
    <li>
      <a href="#">Menu2</a>
      <ul>
        <li><a href="#">Submenu D</a></li>
        <li><a href="#">Submenu E</a></li>
        <li><a href="#">Submenu F</a></li>
      </ul>
    </li>
  </ul>
</div>

And then jQuery like this:

$("#menu li").hover(function() {
  $(this).find("ul").show("fast");
}, function() {
  $(this).find("ul").hide("fast");
});

Then when you hover over the submenus, you actually still hover over the main menu and then it will not close. The above example is also flexible, so you don't have to write it once for each menu.