一个css和js结合的下拉菜单,支持主流浏览器
首先聲明:
? ? ? ?本人盡管在web前端崗位干了好多年,但無奈崗位對(duì)技術(shù)要求不高。html,css用的比較多,JavaScript自己原創(chuàng)的非常少,基本都是copy改動(dòng),所以自己真正動(dòng)手寫時(shí),發(fā)現(xiàn)基礎(chǔ)非常不堅(jiān)固,邊學(xué)習(xí)邊實(shí)踐,收獲非常大。
效果圖:
? ? ? ? 不廢話了,貼碼了
? ? 1、css代碼
a:link{color:white;text-decoration:none;} a:visited{color:white;text-decorative:none;} a:hover{color:white;text-decorative:none;} a:active{color:white;text-decorative:none;} li{float:left;display:inline;background-color:#003366;width:120px;text-align:center;margin:2px;padding:10px 0 5px 0;position:relative;} .limouseover{background-color:#0033ff;color:red;} .limouseout{background-color:#003366;color:black;} li ul{display:none;width:120px;position:absolute;left:0;top:30px;} li ul li{margin:0px auto;border-top:1px solid #006699;}
? ? ?2、JavaScript代碼
<script language=javascript>function menu(menu1){//鼠標(biāo)移入移出classname切換和子菜單隱藏、顯示切換。if (document.getElementById(menu1)){var menu_ul=document.getElementById(menu1);if (menu_ul.getElementsByTagName("li").length){var menu_li=menu_ul.getElementsByTagName("li");for (i in menu_li){menu_li[i].οnmοuseοver=function(){this.className="limouseover";if (this.getElementsByTagName("ul").length){this.getElementsByTagName("ul")[0].style.display="block";}}menu_li[i].οnmοuseοut=function(){this.className="limouseout";if (this.getElementsByTagName("ul").length){this.getElementsByTagName("ul")[0].style.display="none";}}}}}}</script>
? ? 3、html代碼 <ul id=menu1><li><a href="">首頁</a></li><li><a href="">菜單1菜單1</a><ul><li><a href="">子菜單1子菜單1子菜單1子菜單1</a></li><li><a href="">子菜單2</a></li></ul></li><li><a href="">菜單2</a><ul><li><a href="">子菜單1子菜單1子菜單1子菜單1</a></li><li><a href="">子菜單2</a></li></ul></li></ul>
<script>var menu1=new menu("menu1");</script>
說明:
1、考慮到ul和li頁面用的比較多,能夠在css前增加#menu1。以對(duì)菜單樣式進(jìn)行范圍限制。
2、js主要是對(duì)鼠標(biāo)移入和移除事件進(jìn)行了偵聽,相應(yīng)切換到limouseover和limouseout樣式。同一時(shí)候?qū)ψ硬藛蔚膁isplay屬性進(jìn)行更改。達(dá)到顯示隱藏的功能。
3、同一個(gè)頁面能夠反復(fù)調(diào)用。不沖突,html代碼中的JavaScript代碼是調(diào)用實(shí)例。前面的menu1為隨意變量名。括號(hào)內(nèi)的menu1為html頁面中的id。
本例的缺點(diǎn):
1、菜單li的mouseover、mouseout和子菜單li的樣式一樣,即同一個(gè)顏色和字體。沒有實(shí)現(xiàn)單獨(dú)設(shè)置。
2、因?yàn)橐嫒軮e6和ie7,所以當(dāng)中採用position:absolute的同一時(shí)候,添加了left和top屬性。top要依據(jù)菜單li的總體高度設(shè)定。
總結(jié)
以上是生活随笔為你收集整理的一个css和js结合的下拉菜单,支持主流浏览器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL主从失败 错误Got fata
- 下一篇: 实现一个div在浏览器水平居中