mirror of
https://github.com/d0zingcat/NotionNext.git
synced 2026-05-13 23:16:47 +00:00
fix: 修复深色模式下闪烁问题
This commit is contained in:
@@ -2,6 +2,37 @@
|
||||
import BLOG from '@/blog.config'
|
||||
import Document, { Head, Html, Main, NextScript } from 'next/document'
|
||||
|
||||
// 预先设置深色模式的脚本内容
|
||||
const darkModeScript = `
|
||||
(function() {
|
||||
const darkMode = localStorage.getItem('darkMode')
|
||||
|
||||
const prefersDark =
|
||||
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
|
||||
const defaultAppearance = '${BLOG.APPEARANCE || 'auto'}'
|
||||
|
||||
let shouldBeDark = darkMode === 'true' || darkMode === 'dark'
|
||||
|
||||
if (darkMode === null) {
|
||||
if (defaultAppearance === 'dark') {
|
||||
shouldBeDark = true
|
||||
} else if (defaultAppearance === 'auto') {
|
||||
// 检查是否在深色模式时间范围内
|
||||
const date = new Date()
|
||||
const hours = date.getHours()
|
||||
const darkTimeStart = ${BLOG.APPEARANCE_DARK_TIME ? BLOG.APPEARANCE_DARK_TIME[0] : 18}
|
||||
const darkTimeEnd = ${BLOG.APPEARANCE_DARK_TIME ? BLOG.APPEARANCE_DARK_TIME[1] : 6}
|
||||
|
||||
shouldBeDark = prefersDark || (hours >= darkTimeStart || hours < darkTimeEnd)
|
||||
}
|
||||
}
|
||||
|
||||
// 立即设置 html 元素的类
|
||||
document.documentElement.classList.add(shouldBeDark ? 'dark' : 'light')
|
||||
})()
|
||||
`
|
||||
|
||||
class MyDocument extends Document {
|
||||
static async getInitialProps(ctx) {
|
||||
const initialProps = await Document.getInitialProps(ctx)
|
||||
@@ -29,6 +60,9 @@ class MyDocument extends Document {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 预先设置深色模式,避免闪烁 */}
|
||||
<script dangerouslySetInnerHTML={{ __html: darkModeScript }} />
|
||||
</Head>
|
||||
|
||||
<body>
|
||||
|
||||
Reference in New Issue
Block a user