JS實現下拉菜單的功能,實際使用中記得用CSS,性能和代碼都好 ...
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset = "utf8"> 5 <title>JS實現下拉菜單的功能</title> 6 <style> 7 8 .mynav>ul{ 9 list-style-type:none; 10 padding:0; 11 12 } 13 .mynav>ul>li{ 14 float:left; 15 margin:10px 20px ; 16 color:white; 17 18 } 19 .mynav>ul>li>a{ 20 text-decoration:none; 21 color:white; 22 } 23 .dropdown-m{ 24 position:absolute; 25 z-index:99; 26 list-style:none; 27 margin-top:10px; 28 padding:10px; 29 font-size:20px; 30 border:0px solid black; 31 float: none; 32 display:none; 33 box-shadow: 10px 10px 5px #888888; 34 background:lightblue; 35 36 37 } 38 39 .dropdown-m a{ 40 text-decoration:none; 41 color:white; 42 padding:10px; 43 width:100px; 44 display: block; 45 } 46 .dropdown-m li:hover{ 47 background:blue; 48 49 50 } 51 .content{ 52 margin:40px; 53 } 54 button{ 55 cursor: pointer; 56 57 border: none; 58 outline: none; 59 color: white; 60 61 background-color: inherit; 62 } 63 .show{ 64 display:block;//用於class切換 65 } 66 </style> 67 </head> 68 <body> 69 <div class="container" style="background:lightgrey;height:800px"> 70 <nav class="mynav" style="background:black;"> 71 <ul> 72 <li><a href="#">首頁</a></li> 73 <li><a href="#">WEB</a></li> 74 <li><a href="#">演算法</a></li> 75 <li > 76 77 <button onclick="showtoggle()">前端內容</button> 78 79 80 <ul class="dropdown-m" id="dropdown"> 81 <li><a href="#">HTML</a><li> 82 <li><a href="#">CSS</a><li> 83 <li><a href="#">JavaScript</a><li> 84 <li><a href="#">node.js</a><li> 85 </ul> 86 </li> 87 </ul> 88 <div style="clear:both"></div> 89 90 </nav> 91 92 <div class="content"> 93 <dl> 94 <dt>js簡介<dt> 95 96 <dd> JavaScript 是腳本語言</dd> 97 <dd>JavaScript 是一種輕量級的編程語言。</dd> 98 99 <dd>JavaScript 是可插入 HTML 頁面的編程代碼。</dd> 100 101 <dd> JavaScript 插入 HTML 頁面後,可由所有的現代瀏覽器執行。</dd> 102 103 <dd> JavaScript 很容易學習。</dd> 104 105 <dl> 106 </div> 107 </div> 108 <script> 109 //實現切換,hover也是可以,不用這麼麻煩 110 function showtoggle(){ 111 document.getElementById("dropdown").classList.toggle("show"); 112 } 113 //點擊其他區域也關閉 114 window.onclick=funtuion=function(e){ 115 if(!e.target.matches("button")){ 116 var dropdown = document.getElementById("dropdown"); 117 if (dropdown.classList.contains('show')) { 118 dropdown.classList.remove('show'); 119 }} 120 } 121 </script> 122 </body> 123 </html>