如何使用 CSS 创建一个动画的可关闭侧边导航菜单?
要创建一个动画的可关闭侧边导航菜单,需要提供一种机制,以便单击按钮即可关闭和打开它。菜单通过按钮打开,通过“x”关闭。为此使用了事件监听器,并调用函数来设置导航菜单的宽度。
假设网页上有一个这样的按钮:
单击上面的按钮,侧边导航栏就会打开:
创建用于打开菜单的按钮
首先,设置一个按钮来打开导航菜单:
<button class="openSideNav">Click here to open sideNav</button>
单击按钮时,调用函数showNav(),使用事件监听器打开导航菜单:
let openBtn = document.querySelector(".openSideNav"); openBtn.addEventListener("click", () => { showNav(); });
showNav() 函数设置宽度:
function showNav() { document.querySelector(".sideNav").style.width = "300px"; }
创建用于关闭菜单的按钮
要设置关闭按钮,使用“x”来关闭它,并在单击“x”时调用一个函数:
<a href="#" class="closeBtn">×</a>
单击关闭按钮“x”时,将调用hideNav() 函数:
let closeBtn = document.querySelector(".closeBtn"); closeBtn.addEventListener("click", () => { hideNav(); });
hideNav() 函数将宽度设置为隐藏菜单:
function hideNav() { document.querySelector(".sideNav").style.width = "0"; }
设置导航菜单
既然我们知道如何打开和关闭菜单,让我们看看如何设置导航样式:
<nav class="sideNav">
设置导航菜单样式
sideNav 的样式如下所示。这里,height: 100vh; 表示此元素的高度等于视口高度的 100%。位置是固定的,因为我们需要一个固定的导航菜单:
.sideNav { height: 100vh; width: 0; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(46, 218, 195); overflow-x: hidden; padding-top: 60px; transition: 0.5s; }
设置菜单链接样式
链接样式如下:
.sideNav a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #000000; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; display: block; transition: 0.3s; }
示例
以下是创建动画的可关闭侧边导航菜单的代码:
<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .sideNav { height: 100vh; width: 0; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(46, 218, 195); overflow-x: hidden; padding-top: 60px; transition: 0.5s; } .sideNav a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #000000; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; display: block; transition: 0.3s; } .sidenav a:hover { color: #f1f1f1; } .sideNav .closeBtn { position: absolute; top: 0; right: 25px; font-size: 36px; margin-left: 50px; } button { padding: 15px; background-color: rgb(0, 27, 145); color: rgb(255, 255, 255); font-size: 20px; border: none; border-radius: 2%; } </style> </head> <body> <nav class="sideNav"> <a href="#" class="closeBtn">×</a> <a href="#">Login</a> <a href="#">Register</a> <a href="#">Home</a> <a href="#">About Us</a> </nav> <button class="openSideNav">Click here to open sideNav</button> <script> let openBtn = document.querySelector(".openSideNav"); openBtn.addEventListener("click", () => { showNav(); }); let closeBtn = document.querySelector(".closeBtn"); closeBtn.addEventListener("click", () => { hideNav(); }); function showNav() { document.querySelector(".sideNav").style.width = "300px"; } function hideNav() { document.querySelector(".sideNav").style.width = "0"; } </script> </body> </html>
广告