更改主题并将其存储在本地存储中

时间:2019-07-03 13:18:41

标签: javascript css local-storage

我有两个主题“暗”和“浅”,我希望在单击复选框时可以更改主题。

这是我更改主题的方式:

document.documentElement.setAttribute('data-theme', 'dark');

现在,这正在起作用。但是我希望将此更改保存在本地存储中,因此即使重新加载页面后,主题也可以保持不变而不更改。

这是我的代码:

checkBox.addEventListener('change', function () {
    if(this.checked) {

        document.documentElement.setAttribute('data-theme', 'dark');
        localStorage.setItem( 'data-theme', 'dark');   
    }
    else {
        document.documentElement.setAttribute('data-theme', 'light');
        localStorage.setItem('data-theme', 'light');
    }
})

我犯了一个错误还是有我不明白的地方?

3 个答案:

答案 0 :(得分:2)

可以这样尝试:

var checkBox = document.getElementById('cb');

var theme = window.localStorage.getItem('data-theme');
if(theme) document.documentElement.setAttribute('data-theme', theme);
checkBox.checked = theme == 'dark' ? true : false;

checkBox.addEventListener('change', function () {
  if(this.checked){
    document.documentElement.setAttribute('data-theme', 'dark');
    window.localStorage.setItem('data-theme', 'dark');
  } else {
    document.documentElement.setAttribute('data-theme', 'light');
    window.localStorage.setItem('data-theme', 'light');
  }
});
<input id="cb" type="checkbox" />
<label for="cb">Checkbox</label>

答案 1 :(得分:0)

您需要一些有关这些解决方案的步骤:

  • 从localStroge获取先前的设置值
  • 获取复选框元素
  • 如果未设置,则根据先前的本地存储值有条件地设置复选框,然后默认为false

最后设置和取消设置逻辑

var dragTheme = window.localStorage.getItem('dark-theme'); //get the privious seted value
var themeCheckBox = document.getElementById('themeCheck'); // get the checkbox element
themeCheckBox.checked = (dragTheme == "true")? true : false; // set checkbox conditionally base on privious set value if not set then default false

function myFunction() { // triger when change value of checkbox
   if(themeCheckBox.checked) {
      document.documentElement.setAttribute('dark-theme', 'dark');
      window.localStorage.setItem('dark-theme', true);
   }else {
      document.documentElement.setAttribute('dark-theme', 'light');
      window.localStorage.setItem('dark-theme', false);
   }
}
<label for="themeCheck">
  <input type="checkbox" id="themeCheck" onchange="myFunction()" /> Drak Theme
</label>

答案 2 :(得分:0)

好的黑帮,这就是我们要做的事情

将此.js文件添加到您的项目中

export class ThemeManager {
    'use-strict';
    /**
     * Constructs object of class ThemeManager
     * @param {string} themeToggle - the element that changes the website theme on click
     * @param {string} theme - light for initial theme light and vice versa for dark
     */
    constructor(themeToggle, theme = 'light') {
        //get theme toggle DOM node
        if (!themeToggle) {
            console.error(`A valid DOM element must be passed as the themeToggle. You passed ${themeToggle}`);
            return;
        }
        this.themeToggle = themeToggle;
        this.themeToggle.addEventListener('click', () => this.switchTheme());

        //get initial theme and apply it
        this.theme = theme;
        if (localStorage.getItem('data-theme')) {
            if (localStorage.getItem('data-theme') === (theme === 'light' ? 'dark' : 'light')) {
                this.theme = (theme === 'light' ? 'dark' : 'light');
            }
        }
        else if (window.matchMedia(`(prefers-color-scheme: ${(theme === 'light' ? 'dark' : 'light')})`).matches) {
            this.theme = (theme === 'light' ? 'dark' : 'light');
        }
        this._applyTheme();

        //add listener to change web theme on os theme change
        window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', (e) => {
            this.theme = (e.matches ? 'light' : 'dark');
            this._applyTheme();
        });

    }

    /**
     * Private _applyTheme sets documentElement and localStorage 'data-theme' attribute
     * effectively changing the style of the page due to the css changing on 'data-theme'
     */
    _applyTheme = () => {
        this.themeToggle.innerHTML = (this.theme === 'light' ? 'Dark' : 'Light');
        document.documentElement.setAttribute('data-theme', this.theme);
        localStorage.setItem('data-theme', this.theme);
    }

    /**
     * switchTheme toggles the website theme on themeToggle event: 'click'
     */
    switchTheme = () => {
        this.theme = (this.theme === 'light' ? 'dark' : 'light');
        this._applyTheme();
    }
}

将此CSS添加到页面.css文件中

/* Dark/Light Mode Support Modifications
-------------------------------------------------- */
a, a:hover {
    color: var(--link-white-color);
}

.dropdown-menu {
    background: var(--bg-color);
}

.dropdown-item {
    color: var(--link-white-color);
}

hr {
    background-color: var(--link-white-color);
    height: 1px;
    border: 0;
}

/* Dark/Light Mode Support
-------------------------------------------------- */
/*Light*/
:root {
    --font-color: #000;
    --link-color: #1C75B9;
    --link-white-color: #000;
    --bg-color: rgb(243,243,243);
}
/*Dark*/
[data-theme="dark"] {
    --font-color: #c1bfbd;
    --link-color: #0a86da;
    --link-white-color: #c1bfbd;
    --bg-color: #333;
}

现在您在html文件中要做的就是这样:

<html>
    <head>
        <title>your_title</title>
        <link rel="stylesheet" href="path/to/your/css">
    </head>
    <body>
        <button id="themeToggle"></button>
        <script type="module" src="path/to/ThemeManager.js"></script>
        <script type="module">
            import {ThemeManager} from 'path/to/ThemeManager.js';
            new ThemeManager(document.getElementById('themeToggle'));
        </script>
    </body>
</html>