布局: wrap > ul > li*3 (一级菜单123)
wrap > ul > li > a + li*3 (隐藏的)
案例分析:
鼠标经过 , 会显示下拉菜单
鼠标离开, 又会隐藏
关键代码
$(function(){ $(".wrap > ul > li").mouseover(function() { $(this).children("ul").stop().slideDown(); //注意,this是一个jQuery对象,必须外面加一个$,转化成jQuery对象 }) $(".wrap > ul > li").mouseout(function() { $(this).children("ul").stop().slideUp(); }) })
代码优化:
var $li=$(.wrap > ul > li)
完整代码
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style type="text/css"> * { margin: 0; padding: 0; } ul { list-style: none; } .wrap { 330px; height: 30px; margin: 100px auto 0; padding-left: 10px; background-image: url(imgs/bg.jpg); } .wrap li { background-image: url(imgs/libg.jpg); } .wrap > ul > li { float: left; margin-right: 10px; position: relative; } .wrap a { display: block; height: 30px; 100px; text-decoration: none; color: #000; line-height: 30px; text-align: center; } .wrap li ul { position: absolute; top: 30px; display: none; } </style> <script src="jquery-1.12.4.min.js"></script> <script> $(function () { var $li = $(".wrap>ul>li"); //给li注册鼠标经过事件,让自己的ul显示出来 $li.mouseenter(function () { //找到所有的儿子,并且还得是ul $(this).children("ul").show(); }); $li.mouseleave(function () { $(this).children("ul").hide(); }); }); </script> </head> <body> <div class="wrap"> <ul> <li> <a href="javascript:void(0);">一级菜单1</a> <ul class="ul"> <li><a href="javascript:void(0);">二级菜单11</a></li> <li><a href="javascript:void(0);">二级菜单12</a></li> <li><a href="javascript:void(0);">二级菜单13</a></li> </ul> </li> <li> <a href="javascript:void(0);">一级菜单2</a> <ul> <li><a href="javascript:void(0);">二级菜单21</a></li> <li><a href="javascript:void(0);">二级菜单22</a></li> <li><a href="javascript:void(0);">二级菜单23</a></li> </ul> </li> <li> <a href="javascript:void(0);">一级菜单3</a> <ul> <li><a href="javascript:void(0);">二级菜单31</a></li> <li><a href="javascript:void(0);">二级菜单32</a></li> <li><a href="javascript:void(0);">二级菜单33</a></li> </ul> </li> </ul> </div> </body> </html>