JS+CSS如何实现相对定位的下拉菜单?

JS+CSS如何实现相对定位的下拉菜单?

本文实例讲述了JS+CSS相对定位实现的下拉菜单。分享给大家供大家参考。具体如下:

这里使用的是相对定位,不过效果还可以,用时候再修整一下,这个只是实现了大概功能,还有许多细节没有修饰。

运行效果截图如下:

JS+CSS如何实现相对定位的下拉菜单?

在线演示地址如下:

http://demo.jb51.net/js/2015/js-css-ab-fix-menu-codes/

具体代码如下:

<html>
<head>
<title>非定位CSS+Js下拉菜单</title>
<style>
#menu {
 position: absolute;
 font-family: sans-serif;
 font-size: 9pt;
}
#menu li {
 float: left;
 list-style-type: none;
 width: 102px;
 background-color: skyblue;
 border: 1px solid #0066cc;
 text-indent: 0px;
 margin-left: 3px;
}
#menu li a {
 color: blue;
 text-decoration: none;
 width: 100%;
 display: block;
}
#menu li a:hover {
 color: white;
}
#menu li ul {
 background-color: skyblue;
 margin: 0px;
 padding: 0px;
}
#menu li ul li {
 padding: 0px;
 margin: 0px;
 float: none;
 list-style-type: none;
 width: 100px;
 text-indent: 0px;
 border: none;
}
#menu li ul li a{
 color: black;
 text-decoration: none;
}
#menu li ul li a:hover{
 color: black;
 background-color: aqua;
}</style>
<script language="javascript" type="text/javascript">
var t=false,current;
function SetupMenu() {
 if (!document.getElementsByTagName) return;
 items=document.getElementsByTagName("li");
 for (i=0; i<items.length; i++) {
  if (items[i].className != "menu") continue;
  thelink=findChild(items[i],"A");
  thelink.onmouseover=ShowMenu;
  thelink.onmouseout=StartTimer;
  if (ul=findChild(items[i],"UL")) {
   ul.style.display="none";
   for (j=0; j<ul.childNodes.length; j++) {
   ul.childNodes[j].onmouseover=ResetTimer;
   ul.childNodes[j].onmouseout=StartTimer;
   }
  }
 } 
}
function findChild(obj,tag) {
 cn = obj.childNodes;
 for (k=0; k<cn.length; k++) {
  if (cn[k].nodeName==tag) return cn[k];
 }
 return false;
}
function ShowMenu(e) {
 if (!e) var e = window.event;
 thislink = (e.target) ? e.target: e.srcElement;
 ResetTimer();
 if (current) HideMenu(current);
 thislink = thislink.parentNode;
 current=thislink;
 ul = findChild(thislink,"UL");
 if (!ul) return;
 ul.style.display="block";
}
function HideMenu(thelink) {
 ul = findChild(thelink,"UL");
 if (!ul) return;
 ul.style.display="none";
}
function ResetTimer() {
 if (t) window.clearTimeout(t);
}
function StartTimer() {
 t = window.setTimeout("HideMenu(current)",200);
}
window.onload=SetupMenu;
</script>
</head>
<body>
<h1>Menu Test</h1>
<ul id="menu">
<li class="menu"><a href="#">Home</a></li>
<li class="menu"><a href="#">Products</a>
 <ul>
 <li><a href="#">Sub-item 1</a></li>
 <li><a href="#">Sub-item 2</a></li>
 </ul>
</li>
<li class="menu"><a href="#">Support</a>
 <ul>
 <li><a href="#">Sub-item 1</a></li>
 <li><a href="#">Sub-item 2</a></li>
 </ul>
</li>
<li class="menu"><a href="#">Employment</a>
 <ul>
 <li><a href="#">Sub-item 1</a></li>
 <li><a href="#">Sub-item 2</a></li>
 </ul>
</li>
<li class="menu"><a href="#">Contact Us</a>
 <ul>
 <li><a href="#">Sub-item 1</a></li>
 <li><a href="#">Sub-item 2</a></li>
 </ul>
</li>
</ul>
</body>
</html>

希望本文所述对大家的JavaScript程序设计有所帮助。