搜尋
首頁web前端css教學HTML Web 元件中的深色模式切換

在設計我的數位花園時,我知道我想要一個可愛的黑暗模式切換開關。繪製完 SVG 後,我開始建立一個 Web 元件,該元件具有與 React 中的暗模式切換功能相同的功能。這包括我在可訪問性審核我的網站時學到的所有內容。

除了更改主題之外,切換還需要考慮使用者的首選顏色方案選擇,並在重新載入時保留使用者的偏好。為了實現可訪問性,切換的螢幕閱讀器公告必須有意義(例如「深色模式切換開啟」)。由於我想顯示 SVG 而不是帶有文字的複選框,因此我必須添加焦點和懸停樣式以及懸停時顯示的標籤。

切換 Web 元件

首先,我需要一個用於建立 HTML 元素的 Toggle 類別。使用自訂元素 API,我將定義 使用這個類別。

使用類別的建構函數,我設定了 的innerHTML到 有 和 SVG 作為小孩。此標籤具有標題屬性,如果使用者將滑鼠懸停在其上或 上,則會為我們的切換提供可見的「深色模式切換」標籤。因為複選框是

Dark Mode Toggle in HTML Web Components

HTML 就位後,我在該類別中新增一個connectedCallback 函數。自訂元素 API 的這一部分定義了在元件內使用的函數,並在元件插入 DOM 時執行程式碼。

// /components/toggle.js

class Toggle extends HTMLElement {
  constructor() {
    super();
    this.innerHTML = `
      <label title="dark mode toggle">
        <input type="checkbox" id="theme-toggle" class="theme-switch">
        <svg id="daisy">{SVG code removed for brevity}</svg>
      </label>
    `
    this.setAttribute("class", "toggle-component");
  }

  connectedCallback() {
    function switchTheme(e) {
      if (e.target.checked) {
        setTheme('dark');
        return;
      }

      setTheme('light');   
    };

    function setTheme(themeName) {
      localStorage.setItem('theme', themeName);
      document.documentElement.setAttribute('data-theme', themeName);
    };

    function setCheckBox(toggleSwitch, theme) {
      toggleSwitch.checked = theme === 'dark' ? true : false;
    }

    function keepTheme() {
      const toggleSwitch = document.querySelector('#theme-toggle');
      toggleSwitch.addEventListener('change', switchTheme, false);
      const theme = localStorage.getItem('theme');
      if (theme) {
        setTheme(theme);
        setCheckBox(toggleSwitch, theme);
        return;
      };

      const prefersLightTheme = window.matchMedia('(prefers-color-scheme: light)');
      if (prefersLightTheme.matches) {
        setTheme('light');
        return;
      };

      setTheme('dark');
      setCheckBox(toggleSwitch, 'dark');
    };

    document.addEventListener("DOMContentLoaded", keepTheme);    
  }
}

customElements.define("toggle-component", Toggle);

因為 在頁面載入之前插入到 DOM 中,唯一立即執行的程式碼會新增事件偵聽器。頁面載入後,事件偵聽器立即呼叫 keepTheme。首先,keepTheme 將事件偵聽器新增到 中。當使用者與其互動時調用 switchTheme。如果選中該複選框,則 switchTheme 將“dark”傳遞給 setTheme;如果未選中,則將“light”傳遞給 setTheme。傳遞給 setTheme 的字串被設定為 CSS 主題並保存在 localStorage 中,它將在重新載入後持續存在。

keepTheme 的其餘部分致力於在加載時選擇正確的主題。首先,它檢查 localStorage 以查看使用者的首選項是否已設定。接下來,它檢查prefers-color-scheme是否設定為“light”。最後,它預設為深色模式。對於深色和淺色模式,我呼叫 setTheme。對於深色模式,我也調用setCheckbox。此複選框以未選取狀態安裝。螢幕閱讀器將宣布“深色模式”以及是否選中該複選框。要獲得諸如“選中深色模式切換”或“打開深色模式切換”之類的公告,當我在加載時將主題設置為“深色”時,我必須以編程方式選中該複選框。

Dark Mode Toggle in HTML Web Components

Dark Mode Toggle in HTML Web Components

切換樣式

我選擇繪製一個相當簡單的設計,這樣我就可以將 SVG 程式碼直接放入 Web 元件中,並以程式設計方式變更填滿色。這樣,雛菊的背景顏色始終與主體相符。接下來,我使用不透明度:0;隱藏複選框並將其放置在圖像的中間。最後,我添加了懸停和焦點樣式。

Dark Mode Toggle in HTML Web Components

// /components/toggle.js

class Toggle extends HTMLElement {
  constructor() {
    super();
    this.innerHTML = `
      <label title="dark mode toggle">
        <input type="checkbox" id="theme-toggle" class="theme-switch">
        <svg id="daisy">{SVG code removed for brevity}</svg>
      </label>
    `
    this.setAttribute("class", "toggle-component");
  }

  connectedCallback() {
    function switchTheme(e) {
      if (e.target.checked) {
        setTheme('dark');
        return;
      }

      setTheme('light');   
    };

    function setTheme(themeName) {
      localStorage.setItem('theme', themeName);
      document.documentElement.setAttribute('data-theme', themeName);
    };

    function setCheckBox(toggleSwitch, theme) {
      toggleSwitch.checked = theme === 'dark' ? true : false;
    }

    function keepTheme() {
      const toggleSwitch = document.querySelector('#theme-toggle');
      toggleSwitch.addEventListener('change', switchTheme, false);
      const theme = localStorage.getItem('theme');
      if (theme) {
        setTheme(theme);
        setCheckBox(toggleSwitch, theme);
        return;
      };

      const prefersLightTheme = window.matchMedia('(prefers-color-scheme: light)');
      if (prefersLightTheme.matches) {
        setTheme('light');
        return;
      };

      setTheme('dark');
      setCheckBox(toggleSwitch, 'dark');
    };

    document.addEventListener("DOMContentLoaded", keepTheme);    
  }
}

customElements.define("toggle-component", Toggle);

使用切換 Web 元件

我需要做的就是在

中匯入我的樣式表和元件腳本。 HTML 頁面的。然後我可以呼叫 頁面中的任何位置。
/* /styles/styles.css */

[data-theme="light"] {
  --toggle-background: #242D54;
}

[data-theme="dark"] {
  --toggle-background: #282e53;
}

#daisy path {
  fill: var(--toggle-background);
}

.theme-switch {
  position: relative;
  bottom: 30px;
  left: 55px;
  width: 1em;
  height: 1em;
  opacity: 0;
}

.theme-switch:focus + #daisy path,
.theme-switch:hover + #daisy path {
  fill: white;
}

.theme-switch:focus + #daisy {
  outline: 3px solid white;
  outline-offset: 5px;
}

Dark Mode Toggle in HTML Web Components

Dark Mode Toggle in HTML Web Components

結論

我很高興讓我的黑暗模式切換在 Web 元件中像在 React 中一樣工作。您可以在我的數位花園中即時查看此內容,並在 GitHub 儲存庫中查看完整程式碼。

以上是HTML Web 元件中的深色模式切換的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Flexbox vs Grid:我應該學習兩者嗎?Flexbox vs Grid:我應該學習兩者嗎?May 10, 2025 am 12:01 AM

是的,youshouldlearnbothflexboxandgrid.1)flexboxisidealforone-demensional,flexiblelayoutslikenavigationmenus.2)gridexcelstcelsintwo-dimensional,confffferDesignssignssuchasmagagazineLayouts.3)blosebothenHancesSunHanceSlineHancesLayOutflexibilitibilitibilitibilitibilityAnderibilitibilityAndresponScormentilial anderingStruction

軌道力學(或我如何優化CSS KeyFrames動畫)軌道力學(或我如何優化CSS KeyFrames動畫)May 09, 2025 am 09:57 AM

重構自己的代碼看起來是什麼樣的?約翰·瑞亞(John Rhea)挑選了他寫的一個舊的CSS動畫,並介紹了優化它的思維過程。

CSS動畫:很難創建它們嗎?CSS動畫:很難創建它們嗎?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@KeyFrames CSS:最常用的技巧@KeyFrames CSS:最常用的技巧May 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatoryand and powerincreatingsmoothcsssanimations.keytricksinclude:1)definingsmoothtransitionsbetnestates,2)使用AnimatingMultatingMultationMultationProperPertiessimultane,3)使用使用4)使用BombingeNtibalibility,4)使用CombanningWiThjavoFofofofoftofofo

CSS計數器:自動編號的綜合指南CSS計數器:自動編號的綜合指南May 07, 2025 pm 03:45 PM

CSSCOUNTERSAREDOMANAGEAUTOMANAMBERINGINWEBDESIGNS.1)他們可以使用forterablesofcontents,ListItems,and customnumbering.2)AdvancedsincludenestednumberingSystems.3)挑戰挑戰InclassINCludeBrowsEccerCerceribaliblesibility andperformiballibility andperformissises.4)創造性

使用捲軸驅動動畫的現代滾動陰影使用捲軸驅動動畫的現代滾動陰影May 07, 2025 am 10:34 AM

使用滾動陰影,尤其是對於移動設備,是克里斯以前涵蓋的一個微妙的UX。傑夫(Geoff)涵蓋了一種使用動畫限制屬性的新方法。這是另一種方式。

重新訪問圖像圖重新訪問圖像圖May 07, 2025 am 09:40 AM

讓我們快速進修。圖像地圖一直返回到HTML 3.2,首先是服務器端地圖,然後使用映射和區域元素通過圖像上的單擊區域定義了可單擊區域。

DEV狀態:每個開發人員的調查DEV狀態:每個開發人員的調查May 07, 2025 am 09:30 AM

開發委員會調查現已開始參與,並且與以前的調查不同,它涵蓋了除法:職業,工作場所,以及健康,愛好等。 

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3 Mac版

SublimeText3 Mac版

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用