Back on dry land. Take your blog from day to night, no island required!
本頁內容尚未翻譯。
Now that you can build Astro islands for interactive elements, don’t forget that you can go pretty far with just vanilla JavaScript and CSS!
Let’s build a clickable icon to let your users toggle between light or dark mode using another <script>
tag for interactivity… with no framework JavaScript sent to the browser.
Get ready to…
- Build an interactive theme toggle with only JavaScript and CSS
- Send as little JavaScript to the browser as possible!
Add and style a theme toggle icon
Section titled Add and style a theme toggle icon-
Create a new file at
src/components/ThemeIcon.astro
and paste the following code into it: -
Add the icon to
Header.astro
so that it will be displayed on all pages. Don’t forget to import the component. -
Visit your browser preview at
http://localhost:4321
to see the icon now on all your pages. You can try clicking it, but you have not written a script to make it interactive yet.
Add CSS styling for a dark theme
Section titled Add CSS styling for a dark themeChoose some alternate colors to use in dark mode.
-
In
global.css
, define some dark styles. You can choose your own, or copy and paste:
Add client-side interactivity
Section titled Add client-side interactivityTo add interactivity to an Astro component, you can use a <script>
tag. This script can check and set the current theme from localStorage
and toggle the theme when the icon is clicked.
-
Add the following
<script>
tag insrc/components/ThemeIcon.astro
after your<style>
tag: -
Check your browser preview at
http://localhost:4321
and click the theme icon. Verify that you can change between light and dark modes.
Test your knowledge
Section titled Test your knowledgeChoose whether each of the following statements describes Astro <script>
tags, UI framework components, or both.
-
They allow you to include interactive UI elements on your website.
-
They will create static elements on your site unless you include a
client:
to send their JavaScript to the client and run in the browser. -
They allow you to “try out” a new framework without requiring you to start an entirely new project using that tech stack.
-
They allow you to reuse code you have written in other frameworks and you can often just drop them right into your site.
-
They allow you to add interactivity without needing to know or learn any other JavaScript frameworks.