W3School TIY Editor
W3School 在线教程
改变方向
暗黑模式
运行代码
<!DOCTYPE html> <html> <head> <style> .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropbtn:hover, .dropbtn:focus { background-color: #3e8e41; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; overflow: auto; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #f1f1f1} .show {display:block;} </style> </head> <body> <h2>可点击的下拉菜单</h2> <p>单击按钮打开下拉菜单。</p> <div class="dropdown"> <button id="myBtn" class="dropbtn">Dropdown</button> <div id="myDropdown" class="dropdown-content"> <a href="#home">Home</a> <a href="#about">About</a> <a href="#contact">Contact</a> </div> </div> <script> // 获取按钮,当用户点击时,执行 myFunction document.getElementById("myBtn").onclick = function() {myFunction()}; /* myFunction 在添加和删除 show 类之间切换,用于隐藏和显示下拉内容 */ function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } </script> </body> </html>