将你的第一个脚本发送到浏览器
让我们添加一个汉堡菜单来打开和关闭移动屏幕尺寸上的链接,这需要一些客户端交互!
¥Let’s add a hamburger menu to open and close your links on mobile screen sizes, requiring some client-side interactivity!
准备好……
-
创建汉堡菜单组件
-
编写
<script>
以允许你的网站访问者打开和关闭导航菜单 -
将 JavaScript 移至
.js
文件
构建汉堡组件
标题部分 构建汉堡组件¥Build a Hamburger component
创建一个 <Hamburger />
组件来打开和关闭你的移动菜单。
¥Create 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.) -
Place this new
<Hamburger />
component just before your<Navigation />
component inHeader.astro
.Show me the code!
-
Add the following styles for your Hamburger component:
编写你的第一个脚本标签
标题部分 编写你的第一个脚本标签¥Write your first script tag
你的标题尚未交互,因为它无法响应用户输入,例如单击汉堡菜单以显示或隐藏导航链接。
¥Your 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.
添加 <script>
标签可为 “listen” 提供客户端 JavaScript 以处理用户事件,然后做出相应响应。
¥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. -
Check your browser preview again at various sizes, and verify that you have a working navigation menu that is both responsive to screen size and responds to user input on this page.
导入 .js
文件
标题部分 导入 .js 文件¥Importing a .js
file
你可以将 <script>
标记的内容移动到项目中其自己的 .js
文件中,而不是直接在每个页面上编写 JavaScript。
¥Instead of writing your JavaScript directly on each page, you can move the contents of your <script>
tag into its own .js
file in your project.
-
Create
src/scripts/menu.js
(you will have to create a new/scripts/
folder) and move your JavaScript into it. -
Replace the contents of the
<script>
tag onindex.astro
with the following file import: -
Check your browser preview again at a smaller size and verify that the hamburger menu still opens and closes your navigation links.
-
Add the same
<script>
with import to your other two pages,about.astro
andblog.astro
and verify that you have a responsive, interactive header on each page.
测试你的知识
标题部分 测试你的知识¥Test your knowledge
- Astro 什么时候运行在组件的 frontmatter 中编写的任何 JavaScript?
- Astro 可以选择将 JavaScript 发送到浏览器以允许:
- 客户端 JavaScript 在编写或导入时将被发送到用户的浏览器:
清单
标题部分 清单¥Checklist
资源
标题部分 资源¥Resources
Tutorials