案例一:一二级菜单间有空隙
有的时候,在写一级菜单与二级菜单的时候,两个菜单的布局并不是挨着的,中间会因为样式设置,会产生一点高度差,但这种情况很容易在一级菜单获取焦点时二级菜单显示,而一级菜单一失去焦点,二级菜单也跟着消失,这样就点不到二级菜单,不能对二级菜单进行选择,这时脚本的写法可以如下展示:
<div class="topDiv">
<p id="logoImg"><a href="../index.htm"><img src="../static/img/logo.png" /></a></p>
<ul>
<li><a href="../index.htm">首页</a></li>
<li class="active dropList">
<a href="JavaScript:void(0)">产品服务</a>
<ol class="dropWrapper" style="display:none;">
<li class="on"><a>翻译服务</a></li>
<li><a href="message-domestic.html">短信服务</a></li>
</ol>
</li>
</ul>
</div>
//导航显示下拉框
var x = null;
$('.topDiv ul>li.dropList').mouseenter(function () {
$(this).addClass('on');
$(this).find('.dropWrapper').show();
clearTimeout(x);
});
//点击其余位置隐藏导航下拉框
$('.topDiv ul>li.dropList ').mouseleave(function () {
var ths = $(this);
x = setTimeout(function () {
ths.removeClass('on');
ths.find('.dropWrapper').hide();
}, 100)
});
案例二:一级导航 二级导航 显示 和隐藏
<ul class="nav-bd">
<li><a>首页</a></li>
<li><a>新房</a></li>
<li><a>二手房</a></li>
<li>
<a>加盟我们</a>
<span class="second_col">
<a>城市加盟</a>
<a>中介加盟</a>
</span>
</li>
</ul>
<script>
$(document).ready(function(){
//写法 一
$("ul.nav-bd li").mouseover(function(){
$(this).find(".second_col").show();
});
$("ul.nav-bd li").mouseout(function(){
$(this).find(".second_col").hide();
});
//链式写法 二
$("ul.nav-bd li").mouseover(function(){
$(this).find(".second_col").show();
}).mouseout(function(){
$(this).find(".second_col").hide();
});
/*
链式 语法:$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );
*/
//hover写法 三
$("ul.nav-bd li").hover(function(){
$(this).find(".second_col").show();
},function(){
$(this).find(".second_col").hide();
});
/*
链式 语法:$( selector ).hover( handlerIn, handlerOut );
*/
});
</script>
参考资料:.hover() Jquery官方教程 _w3cschool
拓展:绑定事件、解绑事件
//事件绑定
$( selector ).on( "mouseenter mouseleave", handlerInOut );
//事件解绑
$( selector ).off( "mouseenter mouseleave" )
知识点:mouseenter和mouseleave与mouseover和mouseout的区别