javascript實現(xiàn)下拉菜單效果
用Javascript實現(xiàn)下拉菜單,供大家參考,具體內(nèi)容如下
正在學(xué)習(xí)大前端中,有代碼和思路不規(guī)范不正確的地方往多多包涵,感謝指教
下拉菜單,或者側(cè)拉菜單在實際開發(fā)當中非常的實用
代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ padding: 0; margin: 0; border: 0; } .menu{ width: 100%; height: 50px; border: 1px solid lightyellow; box-shadow: 0 2px 5px black; } .menu div{ /*margin-top: 10px;*/ float: left; width: 19.82%; height: 50px; /* border: 1px solid red;*/ text-align: center; } button{ margin-top: 15px; cursor: pointer; width: 25px; height: 15px; background-color: pink; } .show1{ display: none; width: 19.82%; height: 250px; /*border: 1px solid black;*/ } .show1 div{ border: 1px solid pink; width: 247px; height: 48px; text-align: center; } a{ text-decoration: none; display: block; margin-top: 10px; } a:hover{ color: #ff242d; font-size: 25px; } </style> </head> <body> <div class="menu"> <div>下拉1 <button>^</button> </div> <div>下拉2 <button>^</button> </div> <div>下拉3 <button>^</button> </div> <div>下拉4 <button>^</button> </div> <div>下拉5 <button>^</button> </div> </div> <div class="show1"> <div><a href="#" >4654tyyut</a></div> <div><a href="#" >4654</a></div> <div><a href="#" >sdf</a></div> <div><a href="#" >sdf</a></div> <div><a href="#" >tert</a></div> </div> <script> var btn=document.querySelector('button') var show1=document.querySelector('.show1') var flag=0 btn.onclick=function () { if (flag === 0) { show1.style.display = 'block' flag=1 }else { show1.style.display='none' flag=0 } } </script> </body> </html>
代碼解釋
這里主要就是用script的onclick來進行實現(xiàn),這里我用到的按鈕,也可以換成其他的東西,做法都是類似的。
onclick點擊相應(yīng)的東西過后,便會觸發(fā)事件,調(diào)用函數(shù),然后判斷flag的值來進行相應(yīng)的操作,隱藏/顯示div。
這里的flag是關(guān)鍵,這個變量在點擊事件發(fā)生時不斷在0.1之間變化,點擊一次即該函數(shù)被執(zhí)行一次,即循環(huán)一次,也就是判斷flag的值,從而達到顯示/隱藏的效果
演示效果
未下拉時
下拉后
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript中子函數(shù)訪問外部變量的3種解決方法
任何在函數(shù)中定義的變量,都可認為是私有變量,因為不能在函數(shù)外部訪問這些變量,這篇文章主要給大家介紹了關(guān)于JavaScript中子函數(shù)訪問外部變量的3種解決方法,需要的朋友可以參考下2021-06-06一文帶你快速理解JavaScript中call()函數(shù)的使用
這篇文章主要為大家詳細介紹了JavaScript中call()函數(shù)的使用的相關(guān)知識,文中的示例代碼講解詳細,具有一定的學(xué)習(xí)價值,需要的可以參考一下2023-03-03Bootstrap滾動監(jiān)聽組件scrollspy.js使用方法詳解
這篇文章主要為大家詳細介紹了Bootstrap滾動監(jiān)聽組件scrollspy.js的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07