本文實例講述了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程序設計有所幫助。