Send your first script to the browser
本頁內容尚未翻譯。
Let’s add a hamburger menu to open and close your links on mobile screen sizes, requiring some client-side interactivity!
準備好……
- Create a hamburger menu component
- Write a
<script>
to allow your site visitors to open and close the navigation menu - Move your JavaScript to its
.js
file
Build a Hamburger component
Section titled Build a Hamburger componentCreate a <Hamburger />
component to open and close your mobile menu.
-
Create a file named
Hamburger.astro
insrc/components/
-
Copy the following code into your component. This will represent your 3-line “hamburger” menu to open and close your navigation links on mobile. (You will add the new CSS styles to
global.css
later.)src/components/Hamburger.astro ------<div class="hamburger"><span class="line"></span><span class="line"></span><span class="line"></span></div> -
Place this new
<Hamburger />
component just before your<Navigation />
component inHeader.astro
.Show me the code!
src/components/Header.astro ---import Hamburger from './Hamburger.astro';import Navigation from './Navigation.astro';---<header><nav><Hamburger /><Navigation /></nav></header> -
Add the following styles for your Hamburger component:
src/styles/global.css /* nav styles */.hamburger {padding-right: 20px;cursor: pointer;}.hamburger .line {display: block;width: 40px;height: 5px;margin-bottom: 10px;background-color: #ff9776;}.nav-links {width: 100%;top: 5rem;left: 48px;background-color: #ff9776;display: none;margin: 0;}.nav-links a {display: block;text-align: center;padding: 10px 0;text-decoration: none;font-size: 1.2rem;font-weight: bold;text-transform: uppercase;}.nav-links a:hover, a:focus {background-color: #ff9776;}.expanded {display: unset;}@media screen and (min-width: 636px) {.nav-links {margin-left: 5em;display: block;position: static;width: auto;background: none;}.nav-links a {display: inline-block;padding: 15px 20px;}.hamburger {display: none;}}
Write your first script tag
Section titled Write your first script tagYour header is not yet interactive because it can’t respond to user input, like clicking on the hamburger menu to show or hide the navigation links.
Adding a <script>
tag provides client-side JavaScript to “listen” for a user event and then respond accordingly.
-
Add the following
<script>
tag toindex.astro
, just before the closing</body>
tag.src/pages/index.astro <Footer /><script>document.querySelector('.hamburger')?.addEventListener('click', () => {document.querySelector('.nav-links')?.classList.toggle('expanded');});</script></body>