亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
1. Set up the CSS for both themes
2. Add a toggle button in HTML
3. Write JavaScript to handle the toggle
4. Optional: Reflect current state in the button
首頁 web前端 js教程 如何使用 JavaScript 為網(wǎng)站實(shí)現(xiàn)暗模式切換

如何使用 JavaScript 為網(wǎng)站實(shí)現(xiàn)暗模式切換

Oct 12, 2025 am 06:31 AM

答案:通過JavaScript切換CSS類並使用localStorage保存用戶偏好,實(shí)現(xiàn)網(wǎng)站暗黑模式。首先定義.light-mode和.dark-mode樣式,HTML添加切換按鈕,JS監(jiān)聽點(diǎn)擊事件,切換類名並存儲(chǔ)狀態(tài),同時(shí)更新按鈕文本以反映當(dāng)前模式,確保用戶再次訪問時(shí)保持設(shè)置。

How to implement a dark mode toggle for a website with JavaScript

To implement a dark mode toggle on your website using JavaScript, you need to switch between light and dark themes based on user preference. This can be done by toggling a CSS class on the html or body element and saving the user's choice in localStorage so the setting persists across visits.

1. Set up the CSS for both themes

Define styles for both light and dark modes using a class (eg, .dark-mode ). Apply base (light) styles by default and override them when the dark class is present.

/* Default light theme */
body {
  background-color: #ffffff;
  color: #333333;
  transition: background-color 0.3s, color 0.3s;
}
<p>/ <em>Dark theme</em> /
.dark-mode {
background-color: #1a1a1a;
color: #f0f0f0;
}</p>

2. Add a toggle button in HTML

Include a button that users can click to switch modes.

<button id="darkModeToggle">Toggle Dark Mode</button>

3. Write JavaScript to handle the toggle

Use JavaScript to detect clicks, add or remove the dark mode class, and save the user's preference.

const toggleButton = document.getElementById('darkModeToggle');
const body = document.body;
<p>// Check for saved user preference
if (localStorage.getItem('darkMode') === 'enabled') {
body.classList.add('dark-mode');
}</p> <p>// Toggle dark mode and save preference
toggleButton.addEventListener('click', () => {
body.classList.toggle('dark-mode');</p> <p>if (body.classList.contains('dark-mode')) {
localStorage.setItem('darkMode', 'enabled');
} else {
localStorage.setItem('darkMode', 'disabled');
}
});</p>

4. Optional: Reflect current state in the button

Update the button text to show whether dark mode is active.

function updateButton() {
  if (body.classList.contains('dark-mode')) {
    toggleButton.textContent = 'Light Mode';
  } else {
    toggleButton.textContent = 'Dark Mode';
  }
}
<p>// Call this after toggling
toggleButton.addEventListener('click', () => {
body.classList.toggle('dark-mode');
updateButton();
localStorage.setItem('darkMode', body.classList.contains('dark-mode') ? 'enabled' : 'disabled');
});</p> <p>// Initial button state
updateButton();</p>

Basically just use a class to control styling, JavaScript to respond to interaction, and localStorage to remember the choice. That way, users get a consistent experience every time they visit.

以上是如何使用 JavaScript 為網(wǎng)站實(shí)現(xiàn)暗模式切換的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門話題

JavaScript實(shí)現(xiàn)點(diǎn)擊圖片切換效果:專業(yè)教程 JavaScript實(shí)現(xiàn)點(diǎn)擊圖片切換效果:專業(yè)教程 Sep 18, 2025 pm 01:03 PM

本文將介紹如何使用JavaScript實(shí)現(xiàn)點(diǎn)擊圖片切換的效果。核心思路是利用HTML5的data-*屬性存儲(chǔ)備用圖片路徑,並通過JavaScript監(jiān)聽點(diǎn)擊事件,動(dòng)態(tài)切換src屬性,從而實(shí)現(xiàn)圖片切換。本文將提供詳細(xì)的代碼示例和解釋,幫助你理解和掌握這種常用的交互效果。

如何使用JavaScript中的GeOlocation API獲取用戶的位置? 如何使用JavaScript中的GeOlocation API獲取用戶的位置? Sep 21, 2025 am 06:19 AM

首先檢查瀏覽器是否支持GeolocationAPI,若支持則調(diào)用getCurrentPosition()獲取用戶當(dāng)前位置坐標(biāo),並通過成功回調(diào)獲取緯度和經(jīng)度值,同時(shí)提供錯(cuò)誤回調(diào)處理權(quán)限被拒、位置不可用或超時(shí)等異常,還可傳入配置選項(xiàng)以啟用高精度、設(shè)置超時(shí)時(shí)間和緩存有效期,整個(gè)過程需用戶授權(quán)並做好相應(yīng)錯(cuò)誤處理。

NUXT 3組成API解釋了 NUXT 3組成API解釋了 Sep 20, 2025 am 03:00 AM

Nuxt3的CompositionAPI核心用法包括:1.definePageMeta用於定義頁面元信息,如標(biāo)題、佈局和中間件,需在中直接調(diào)用,不可置於條件語句中;2.useHead用於管理頁面頭部標(biāo)籤,支持靜態(tài)和響應(yīng)式更新,需與definePageMeta配合實(shí)現(xiàn)SEO優(yōu)化;3.useAsyncData用於安全地獲取異步數(shù)據(jù),自動(dòng)處理loading和error狀態(tài),支持服務(wù)端和客戶端數(shù)據(jù)獲取控制;4.useFetch是useAsyncData與$fetch的封裝,自動(dòng)推斷請(qǐng)求key,避免重複請(qǐng)

如何在JavaScript中使用setInterval創(chuàng)建重複間隔 如何在JavaScript中使用setInterval創(chuàng)建重複間隔 Sep 21, 2025 am 05:31 AM

要?jiǎng)?chuàng)建JavaScript中的重複間隔,需使用setInterval()函數(shù),它會(huì)以指定毫秒數(shù)為間隔重複執(zhí)行函數(shù)或代碼塊,例如setInterval(()=>{console.log("每2秒執(zhí)行一次");},2000)會(huì)每隔2秒輸出一次消息,直到通過clearInterval(intervalId)清除,實(shí)際應(yīng)用中可用於更新時(shí)鐘、輪詢服務(wù)器等場景,但需注意最小延遲限制、函數(shù)執(zhí)行時(shí)間影響,並在不再需要時(shí)及時(shí)清除間隔以避免內(nèi)存洩漏,特別是在組件卸載或頁面關(guān)閉前應(yīng)清理,確保

如何將文本複製到JavaScript中的剪貼板? 如何將文本複製到JavaScript中的剪貼板? Sep 18, 2025 am 03:50 AM

使用ClipboardAPI的writeText方法可複製文本到剪貼板,需在安全上下文和用戶交互中調(diào)用,支持現(xiàn)代瀏覽器,舊版可用execCommand降級(jí)處理。

如何在JavaScript中創(chuàng)建多行字符串? 如何在JavaScript中創(chuàng)建多行字符串? Sep 20, 2025 am 06:11 AM

thebestatoreateamulti-linestlinginjavascriptsisisingsistisingtemplatalalswithbacktticks,whatpreserveticks,whatpreservereakeandeexactlyaswrite。

如何在JavaScript中創(chuàng)建和使用立即調(diào)用的函數(shù)表達(dá)式(IIFE) 如何在JavaScript中創(chuàng)建和使用立即調(diào)用的函數(shù)表達(dá)式(IIFE) Sep 21, 2025 am 05:04 AM

Aniife(立即InvokedFunction表達(dá))IsafunctionThatrunSassoonAsisition定義,createByWrappingAppappingAptappafunctionInparenthensessandMmedImmedImmedInvokingit,whopreventsglobalnamespacepacepallutionpallutionpallutionPollutionPollutionPollutionAndEnablesPrivatesScopethroughCloseconscopethroughClosecome; itiswritten; itiswritten; itiswrittenas(iTiswrittenas;

如何將JSON字符串解析到JavaScript對(duì)像中 如何將JSON字符串解析到JavaScript對(duì)像中 Sep 21, 2025 am 05:43 AM

要將JSON字符串解析為JavaScript對(duì)象,應(yīng)使用JSON.parse()方法,它能將有效的JSON字符串轉(zhuǎn)換為對(duì)應(yīng)的JavaScript對(duì)象,支持嵌套對(duì)象和數(shù)組的解析,但對(duì)無效JSON會(huì)拋出錯(cuò)誤,因此需用try...catch處理異常,同時(shí)可通過第二個(gè)參數(shù)的reviver函數(shù)在解析時(shí)轉(zhuǎn)換值,如將日期字符串轉(zhuǎn)為Date對(duì)象,從而實(shí)現(xiàn)安全可靠的數(shù)據(jù)轉(zhuǎn)換。

See all articles