第一个小demo
$(function(){
var qq = $('qq');
var title = $('title');
var timer = null;
qq.onmouseover = show;
qq.onmouseout = hide;
title.onmouseover = show;
title.onmouseout = hide;
function show(){
clearInterval( timer );
title.style.display = 'block';
}
function hide(){
timer = setTimeout(function(){
title.style.display = 'none';
}, 200);
}
});
完整实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS横向延时2级下拉菜单</title>
<style>
body{ font-size: 12px; color: #333;}
body, ul,h2{ margin:0;padding:0;}
li { list-style:none;}
a{ color: #333; text-decoration: none;}
a:hover{ color: #f00;}
#nav { width:100%; border:1px solid #000; margin-bottom:10px;}
#nav li{ display:inline-block; margin:10px 20px; font-size: 16px; font-weight: bold;}
.nav li { float:left; margin: 0 5px; font-size:12px;}
.nav { position:absolute; border:1px solid #666; padding: 5px; display:none;}
.n1 { left:0;}
.n2 { left:80px;}
.n3 { left:200px;}
</style>
</head>
<body>
<div class="menu">
<ul id="nav">
<li><a href="#">首页</a></li>
<li><a href="#">产品中心</a></li>
<li><a href="#">关于我们</a></li>
</ul>
<ul class="nav n1">
<li><a href="#">首页二级菜单1</a></li>
<li><a href="#">首页二级菜单2</a></li>
<li><a href="#">首页二级菜单3</a></li>
</ul>
<ul class="nav n2">
<li><a href="#">产品中心二级菜单1</a></li>
<li><a href="#">产品中心二级菜单2</a></li>
<li><a href="#">产品中心二级菜单3</a></li>
<li><a href="#">产品中心二级菜单4</a></li>
</ul>
<ul class="nav n3">
<li><a href="#">关于我们二级菜单1</a></li>
<li><a href="#">关于我们二级菜单2</a></li>
</ul>
</div>
<script>
window.onload = function(){
var oUl = document.getElementById('nav');
var aLi = oUl.getElementsByTagName('li'); //获取一级菜单
var aUl = document.getElementsByTagName('ul'); //获取所有ul
var timer = null;
var that = '';
// 循环遍历所有的一级菜单
for(var i = 0; i < aLi.length; i++){
// 这里加1的原因是第0个li所对应的ul是第1个ul
aLi[i].index = i + 1;
// 鼠标经过,先关闭定时器,所有2级菜单隐藏,当前2级菜单显示
aLi[i].onmouseover = function(){
clearTimeout(timer);
// 这里设置i = 1也是和上面一样,一一对应
for(var i = 1; i< aUl.length; i++){
aUl[i].style.display = 'none';
}
aUl[this.index].style.display = 'block';
};
// 鼠标移开时,先延时200毫秒,然后将2级菜单隐藏
aLi[i].onmouseout = function(){
//将当前索引值保存到that变量中
that = this.index;
timer = setTimeout(function(){
aUl[that].style.display = 'none';
},200);
};
}
// 循环遍历所有的二级菜单【原理同上】
for(var i = 1; i < aUl.length; i++){
// 鼠标经过2级菜单,先清空定时器,当前显示
aUl[i].onmouseover = function(){
clearTimeout(timer);
this.style.display = 'block';
};
// 鼠标移开2级菜单,延时200毫秒后再隐藏2级菜单
aUl[i].onmouseout = function(){
that = this;
timer = setTimeout(function(){
that.style.display = 'none';
},200);
}
}
};
</script>
</body>
</html>