点击响应式菜单栏时切换Font Awesome图标(fa-bars转fa-plus)
No problem at all! To swap the menu icon between fa-bars and fa-plus when toggling the responsive menu, we just need to extend your existing JavaScript function to target the icon element and switch its Font Awesome classes. Here's the updated code with clear explanations:
Updated JavaScript
function myFunction() { var x = document.getElementById("myTopnav"); // Grab the Font Awesome icon element inside the menu toggle link var menuIcon = document.querySelector(".topnav .icon i"); if (x.className === "topnav") { x.className += " responsive"; // Switch from bars icon to plus icon menuIcon.classList.remove("fa-bars"); menuIcon.classList.add("fa-plus"); } else { x.className = "topnav"; // Switch back to bars icon menuIcon.classList.remove("fa-plus"); menuIcon.classList.add("fa-bars"); } }
Full Working Code Snippet
HTML
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <div class="topnav" id="myTopnav"> <a href="#home" class="active">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a> <a href="javascript:void(0);" class="icon" onclick="myFunction()"> <i class="fa fa-bars"></i> </a> </div> <div style="padding-left:16px"> <h2>Responsive Topnav Example</h2> <p>Resize the browser window to see how it works.</p> </div> </body> </html>
CSS
body { margin: 0; font-family: Arial, Helvetica, sans-serif; } .topnav { overflow: hidden; background-color: #333; } .topnav a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover { background-color: #ddd; color: black; } .active { background-color: #4CAF50; color: white; } .topnav .icon { display: none; } @media screen and (max-width: 600px) { .topnav a:not(:first-child) {display: none;} .topnav a.icon { float: right; display: block; } } @media screen and (max-width: 600px) { .topnav.responsive {position: relative;} .topnav.responsive .icon { position: absolute; right: 0; top: 0; } .topnav.responsive a { float: none; display: block; text-align: left; } }
How It Works
- We use
document.querySelector(".topnav .icon i")to target the exact Font Awesome icon element inside the menu toggle link. - When we expand the menu (adding the
responsiveclass to the topnav), we swap out thefa-barsclass forfa-plus. - When we collapse the menu (reverting to the default
topnavclass), we switch the icon classes back tofa-bars.
This will smoothly toggle the icon as the menu opens and closes on mobile screens.
内容的提问来源于stack exchange,提问作者Tahsin Ali Jafri
相关产品推荐
相关产品推荐

