所以基本上我有一个菜单,在你将鼠标悬停在上面时,它会展开。我该如何重写我的代码,使其在点击时也能展开(点击后展开,再次点击收缩)?如有必要,可以使用JavaScript,但我一直在尝试只用HTML和CSS来完成所有操作。
html, body { font-family: Arial, Helvetica, sans-serif; } .navigation { width: 300px; } .mainmenu, .submenu { list-style: none; padding: 0; margin: 0; } .mainmenu a { display: block; background-color: #CCC; text-decoration: none; padding: 10px; color: #000; } .mainmenu a:hover { background-color: #C5C5C5; } .mainmenu li:hover .submenu { display: block; max-height: 200px; } .submenu a { background-color: #999; } .submenu a:hover { background-color: #666; } .submenu { overflow: hidden; max-height: 0; -webkit-transition: all 0.5s ease-out; }
<nav class="navigation"> <ul class="mainmenu"> <li><a href="">产品</a> <ul class="submenu"> <li><a href="">上装</a></li> <li><a href="">下装</a></li> <li><a href="">鞋类</a></li> </ul> </li> <li><a href="">其他</a> <ul class="submenu"> <li><a href="">联系我们</a></li> <li><a href="">关于我们</a></li> <li><a href="">常见问题</a></li> </ul> </li> </ul> </nav>
P粉3203612012024-01-17 09:26:48
我仔细阅读了你的问题详情
你可以尝试按照以下修复代码。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> html, body { font-family: Arial, Helvetica, sans-serif; } .navigation { width: 300px; } .mainmenu, .submenu { list-style: none; padding: 0; margin: 0; } .mainmenu a { display: block; background-color: #CCC; text-decoration: none; padding: 10px; color: #000; } .mainmenu a:hover { background-color: #C5C5C5; } .mainmenu li.active .submenu { display: block; max-height: 200px; } .submenu a { background-color: #999; } .submenu a:hover { background-color: #666; } .submenu { overflow: hidden; max-height: 0; -webkit-transition: all 0.5s ease-out; } </style> <body> <nav class="navigation"> <ul class="mainmenu"> <li><a href="javascript:;" onclick="showSubMenu(event)">产品</a> <ul class="submenu"> <li><a href="">上装</a></li> <li><a href="">下装</a></li> <li><a href="">鞋类</a></li> </ul> </li> <li><a href="javascript:;" onclick="showSubMenu(event)">其他</a> <ul class="submenu"> <li><a href="">联系我们</a></li> <li><a href="">关于我们</a></li> <li><a href="">常见问题解答</a></li> </ul> </li> </ul> </nav> </body> <script> function showSubMenu(e) { e.target.parentNode.classList.toggle('active'); } </script> </html>