js定时器(二)延时消失的菜单

来源:互联网 发布:道路工程测量软件 编辑:程序博客网 时间:2024/05/16 18:56

这个小练习,我有点偷懒了=.=.

一.要实现的效果

这个效果和之前的简易qq面板有些类似
1.点击导航延时出现子列表
2.子列表延时消失
3.鼠标放在子列表上,子列表不消失

二.效果图

这里写图片描述

三.代码

1.css

<style type="text/css">body,ul,li,span,a{margin: 0;padding: 0;}li{list-style: none;}#div1{width: 500px;height: 50px;background: rgba(33,90,156,.8);margin: 150px auto; border-radius: 10px;box-shadow: 2px -2px 5px #eee;position: relative;}#div1 #nav{width: 360px; height: 50px;}#div1 #nav li{width: 90px;height: 50px;float: left;color: white;line-height: 50px;text-align: center;cursor:pointer;}#div1 #nav .active{background: #eee;color: black;}#div1 span{display:inline-block;float: right;position: absolute;right: 10px;top: 0;width: 50px;height: 50px;line-height: 50px;text-align: center;color: white;cursor: pointer;}#div2{width: 200px;height: 50px;background:#eee;border-radius: 10px;margin: -140px auto;display: none;}#div2 a{text-decoration: none;display: inline-block;float: left;width:50px;height: 50px;line-height: 50px;text-align: center;}</style>

2.html

<body>    <div id="div1">        <ul id="nav">            <li>首页</li>            <li>作品</li>            <li>博客</li>            <li>关于我们</li>        </ul>        <span>更多</span>    </div>    <div id="div2">        <a href="">1</a>        <a href="">2</a>        <a href="">3</a>        <a href="">4</a>    </div></body>

3.js

<script type="text/javascript">    window.onload=function(){        var div1=document.getElementById('div1');        var oUl=div1.getElementsByTagName('ul');        var oLi=oUl[0].getElementsByTagName('li');        var div2=document.getElementById('div2');        var oA=div2.getElementsByTagName('a')[0];        var oldNum=0;        var time=null;        /*点击li出现a*/        function fn(n){            oLi[oldNum].className='';            oLi[n].className='active';            oldNum=n;        }        fn(0);        for (var i = 0; i < oLi.length; i++) {            oLi[i].index=i;            oLi[i].onmouseover=function(){                clearInterval(time);                div2.style.display='block';                fn(this.index);            }            oLi[i].onmouseout=function(){                time=setInterval(function(){                    div2.style.display='none';                },500);            }            div2.onmouseover=function(){                clearInterval(time);                div2.style.display='block';            }            div2.onmouseout=function(){                time=setInterval(function(){                    div2.style.display='none';                },500);            }        }    }    </script>
原创粉丝点击