【前言】
简单介绍下如何利用jQuery实现二级导航
本文主要通过两种方案实现
注意:hover = mouseenter + mouseleave
补充:(mouseover:当鼠标指针位于元素上方时,会发生 mouseover 事件。 mouseenter:当鼠标指针穿过元素时,会发生 mouseenter 事件。
从这里的一个小插曲上,我们应该可以看出,mouseenter是穿过,所以只能触发一次改事件,而mouseover是位于上方,可以想下,如果给div设定了一个mouseover事件,其子孙后代都可以响应改事件,so...一旦鼠标从父级进入自己也会触发这个效果,当从子集回到父级也会触发这种效果。所以,你可以这么理解:mouseenter事件只作用于目标元素,而mouseover作用于目标元素及其后代元素。)
【主体】
(1)利用jQuery的hover()方法
优点:可以实现过渡效果,并结合css3的动画,达到绚丽的效果
缺点:jQuery兼容局限性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
li{
list-style: none;
}
a{
text-decoration: none;
}
.nav{
width: 80%;
height: 40px;
line-height: 40px;
margin: auto;
}
.nav>li{
float: left;
min-width: 150px;
position: relative;
padding-bottom: 10px;
}
.nav>li>a{
display: block;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.3);
text-align: center;
color: white;
}
.nav>li>ul{
position: absolute;
top: 50px;
background: rgba(0,0,0,0.2);
min-width: 150%;
left: -25%;
height: auto;
display: none;
}
.nav>li>ul>li>a{
text-align: center;
display: block;
width: 100%;
height: 100%;
color: white;
}
.nav>li>a:hover{
background: rgba(0,0,0,0.4);
}
/*.nav>li:hover ul{*/
/*display: block;*/
/*height: 200px;*/
/*}*/
.nav>li>ul>li>a:hover{
background: rgba(0,0,0,0.4);
}
</style>
<link rel="stylesheet" type="text/css" href="img/animate.css">
</head>
<body>
<!-- CSS实现的缺点很明显:二级导航无法实现过渡效果,高度变化由0变auto的过程和display由none变block一样,无法实现过渡。
注意:高度变化若想出现过渡效果,需要由0变到指定高度,如0-200px等才可以。 -->
<ul class="nav">
<li>
<a href="#">首页</a>
</li>
<li>
<a href="#">简介</a>
<ul>
<li><a href="#">创建时间</a></li>
<li><a href="#">上市时间</a></li>
<li><a href="#">风投时间</a></li>
</ul>
</li>
<li>
<a href="#">应聘</a>
<ul>
<li><a href="#">技术岗</a></li>
<li><a href="#">管理岗</a></li>
<li><a href="#">人资岗</a></li>
</ul>
</li>
<li>
<a href="#">产品</a>
<ul>
<li><a href="#">产品名称</a></li>
<li><a href="#">产品来源</a></li>
<li><a href="#">产品功效</a></li>
<li><a href="#">市场效益</a></li>
</ul>
</li>
<li><a href="#">关于我们</a></li>
</ul>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".nav").children('li').hover(function() {
/* Stuff to do when the mouse enters the element */
$(this).children('ul').stop().addClass('animated rollIn').slideDown(400);
}, function() {
/* Stuff to do when the mouse leaves the element */
$(this).children('ul').stop().addClass('rollOut').slideUp(400,function(){
$(this).removeClass('animated rollIn rollOut')
});
});
})
</script>
</body>
</html>
(2)jQuery的鼠标移入移出事件,mouseenter和mouseleave事件,这里之所以不用mouseover和mouseout是因为该事件会产生冒泡,出现二级导航闪动的BUG
$(function(){ $(".nav").children('li').mouseenter(function(event) { /* Act on the event */ $(this).children('ul').stop().addClass('animated rollIn').slideDown(400); }); $(".nav").children('li').mouseleave(function(event) { /* Act on the event */ $(this).children('ul').stop().addClass('rollOut').slideUp(400,function(){ $(this).removeClass('animated rollIn rollOut') }); }); })
.