+
Skip to content

Commit bb59cdc

Browse files
committed
feat: add useDisableTransition to transition between themes smoothly
1 parent 463a280 commit bb59cdc

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

src/components/ui/ThemeToggle.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
import { Show, onMount } from 'solid-js'
2-
import { useDark } from '@/hooks'
2+
import { useDark, useDisableTransition } from '@/hooks'
33

44
export default () => {
55
const [isDark, setIsDark] = useDark()
6+
const { disableTransition, removeDisableTransition } = useDisableTransition()
67

78
onMount(() => {
89
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', isDark() ? '#222222' : '#fafafa')
910
})
1011

1112
const handleDarkChanged = () => {
13+
disableTransition()
1214
const dark = !isDark()
1315
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', dark ? '#222222' : '#fafafa')
1416
setIsDark(dark)
17+
removeDisableTransition()
1518
}
1619

1720
return (

src/hooks/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ export * from './useCopy'
33
export * from './useClickOutside'
44
export * from './useLargeScreen'
55
export * from './useMobileScreen'
6+
export * from './useDisableTransition'

src/hooks/useDisableTransition.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
export const useDisableTransition = () => {
2+
// https://paco.me/writing/disable-theme-transitions
3+
const css = document.createElement('style')
4+
const disableTransition = () => {
5+
css.type = 'text/css'
6+
css.appendChild(
7+
document.createTextNode(
8+
`* {
9+
-webkit-transition: none !important;
10+
-moz-transition: none !important;
11+
-o-transition: none !important;
12+
-ms-transition: none !important;
13+
transition: none !important;
14+
}`,
15+
),
16+
)
17+
document.head.appendChild(css)
18+
}
19+
20+
// Calling getComputedStyle forces the browser to redraw
21+
const removeDisableTransition = () => {
22+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
23+
const _ = window.getComputedStyle(css).opacity
24+
document.head.removeChild(css)
25+
}
26+
27+
return {
28+
css,
29+
disableTransition,
30+
removeDisableTransition,
31+
}
32+
}

0 commit comments

Comments
 (0)
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载