electron (二) 暗黑模式
生活随笔
收集整理的這篇文章主要介紹了
electron (二) 暗黑模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前置代碼:electron (一) 快速入門
首先,讓我們編輯我們的接口,以便可以在光線和暗色的 模式之間切換。 這個基本的界面包含更改 原生主題 設置的按鈕,并且包含一個文本元素,指明了哪些 主題 值被選中
將以下內容添加到 index.html 文件:
<!doctype html> <html lang="cn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>electron</title><link rel="stylesheet" type="text/css" href="style.css"></head><body><h1>hello world</h1><p>當前主題: <strong id="theme-source">系統默認</strong></p><button id="toggle-dark-mode">切換暗黑模式</button><button id="reset-to-system">重置為系統默認</button><script src="renderer.js"></script></body> </html>接下來,添加renderer.js文件,設置按鈕點擊方法:
const { ipcRenderer } = require('electron')document.getElementById('toggle-dark-mode').addEventListener('click', async () => {const isDarkMode = await ipcRenderer.invoke('dark-mode:toggle')document.getElementById('theme-source').innerHTML = isDarkMode ? '暗色' : '明亮'})document.getElementById('reset-to-system').addEventListener('click', async () => {await ipcRenderer.invoke('dark-mode:system')document.getElementById('theme-source').innerHTML = '系統默認' })然后在創建窗口里將點擊事件注冊到渲染進程中,這里是main.js
const { app, BrowserWindow, ipcMain, nativeTheme } = require('electron')function createWindow() {//創建瀏覽器窗口const win = new BrowserWindow({width: 800,height: 600,webPreferences: {nodeIntegration: true,contextIsolation: false,}})//為應用加載index.htmlwin.loadFile('index.html')ipcMain.handle('dark-mode:toggle', () => {if (nativeTheme.shouldUseDarkColors) {nativeTheme.themeSource = 'light'} else {nativeTheme.themeSource = 'dark'}return nativeTheme.shouldUseDarkColors})ipcMain.handle('dark-mode:system', () => {nativeTheme.themeSource = 'system'})//打開開發者工具win.webContents.openDevTools()}最后創建style.css文件,自定義背景色和字體顏色
@media(prefers-color-scheme:dark){body{background:#333;color:white} }@media(prefers-color-scheme:light){body{background:#fff;color:black} }啟動 Electron 應用程序后,你可以通過點擊相應按鈕更改模式或將 主題重置為系統默認值。
總結
以上是生活随笔為你收集整理的electron (二) 暗黑模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: APP如何实现「年轻化」的需求?
- 下一篇: 一网通办的内涵解构