Skip to content

Commit

Permalink
fix: Move data-color-mode to the <html> node.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaywcjlove committed Mar 16, 2022
1 parent f71bc9c commit 2fbb3c9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ const toggle = document.querySelector('dark-mode');
const button = document.createElement('button');
button.textContent = 'Change Theme';
button.onclick = () => {
const theme = document.body.dataset.colorMode;
const theme = document.documentElement.dataset.colorMode;
// or => const theme = toggle.mode
document.body.setAttribute('data-color-mode', theme === 'light' ? 'dark' : 'light');
document.documentElement.setAttribute('data-color-mode', theme === 'light' ? 'dark' : 'light');
}
document.body.appendChild(button);
// Listen for toggle changes
Expand All @@ -84,6 +84,10 @@ export class DarkMode extends HTMLElement {
}
```

## Events

- `colorschemechange`: Fired when the color scheme gets changed.

## Contributors

As always, thanks to our amazing contributors!
Expand Down
14 changes: 7 additions & 7 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ class DarkMode extends HTMLElement {
}

const observer = new MutationObserver((mutationsList, observer) => {
this.mode = document.body.dataset.colorMode;
this.mode = doc.documentElement.dataset.colorMode;
this._changeContent();
this._dispatchEvent(COLOR_SCHEME_CHANGE, { colorScheme: this.mode });
});
// 以上述配置开始观察目标节点
observer.observe(doc.body, { attributes: true });
// 之后,可停止观察
// Start observing the target node with the above configuration
observer.observe(doc.documentElement, { attributes: true });
// After that, stop observing
// observer.disconnect();
this._initializeDOM();
}
Expand All @@ -55,7 +55,7 @@ class DarkMode extends HTMLElement {
}
}
_changeThemeTag() {
doc.body.setAttribute('data-color-mode', this.mode);
doc.documentElement.setAttribute('data-color-mode', this.mode);
}
_changeContent() {
this.icon.textContent = this.mode === 'light' ? '🌒' : '🌞';
Expand All @@ -79,15 +79,15 @@ class DarkMode extends HTMLElement {
this._changeContent();

const textContent = `
[data-color-mode*='dark'] {
[data-color-mode*='dark'], [data-color-mode*='dark'] body {
color-scheme: dark;
--color-thme-bg: #0d1117;
--color-thme-text: #c9d1d9;
background-color: var(--color-thme-bg);
color: var(--color-thme-text);
}
[data-color-mode*='light'] {
[data-color-mode*='light'], [data-color-mode*='light'] body {
color-scheme: light;
--color-thme-bg: #fff;
--color-thme-text: #24292f;
Expand Down

0 comments on commit 2fbb3c9

Please sign in to comment.