<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> *{ margin:0; padding:0; font-family:"微软雅黑"; font-size:18px;} a{text-decoration:none;} .popmenu { 400px; margin:50px auto;} .popmenu ul { background:#B10000; height:25px; } .popmenu ul li{float:left; 100px; position:relative;list-style:none;} .popmenu ul li a{display:block;height:25px; line-height:25px; text-align:center; color:white;} .popmenu ul li a:hover{ background:#79951A; } .popmenu ul li div{display:none; line-height:30px;100px; background:#528DF1; position:absolute;} </style> </head> <body> <div class="popmenu" id="popmenu"> <ul> <li> <a class="first" href="#">菜单1</a> <div> <a href="http://www.baidu.com">吃饭</a> <a href="http://www.qq.com">睡觉</a> <a href="http://www.baidu.com">吃饭</a> <a href="http://www.qq.com">睡觉</a> <a href="http://www.baidu.com">吃饭</a> <a href="http://www.qq.com">睡觉</a> <a href="http://www.baidu.com">吃饭</a> <a href="http://www.qq.com">睡觉</a> </div> </li> <li> <a href="#">菜单2</a> <div> <a href="http://www.baidu.com">吃饭</a> <a href="http://www.qq.com">睡觉</a> <a href="http://www.baidu.com">打豆豆</a> </div></li> <li><a href="#">菜单3</a><div>content3</div></li> <li><a href="#">菜单4</a><div>content4</div></li> </ul> </div> </body> </html> <script> //获取firstchild function firstChild(elem) { var node = elem.firstChild ? elem.firstChild : null; while(node && node.nodeType != 1) { node = node.nextSibling; } return node; } //获取下一个同辈元素(ie下回忽略空白文节点) function next(elem) { var node = elem.nextSibling ? elem.nextSibling : null; while(node && node.nodeType != 1 ) { node = node.nextSibling; } return node; } //获取上一个同辈元素(ie下回忽略空白文节点) function prev(elem) { var node = elem.previousSibling ? elem.previousSibling : null; while(node && node.nodeType != 1 ) { node = node.previousSibling; } return node; } function contains(a,b) { if(document.defaultView) { return !!( a.compareDocumentPosition(b) & 16 ); }else{ return a != b && a.contains(b); } } /** children:只有元素节点 childNodes:所有节点 两个都不存在兼容性问题 */ var lis = document.getElementById('popmenu').getElementsByTagName('li'); for(var i=0;i<lis.length;i++) { lis[i].onmouseover = function(evt){ var evt = evt || window.event; evt.relatedTarget = evt.relatedTarget || evt.fromElement; if(!evt.relatedTarget || !contains(this, evt.relatedTarget)) { //console.log('over') next(firstChild(this)).style.display = 'block'; } } lis[i].onmouseout = function(evt){ var evt = evt || window.event; evt.relatedTarget = evt.relatedTarget || evt.toElement; if( !evt.relatedTarget || (evt.relatedTarget && !contains(this, evt.relatedTarget))) { //console.log('out') next(firstChild(this)).style.display = 'none'; } } } </script>
效果图: