【问题标题】:To keep the checkbox checked once checked while browsing entire website在浏览整个网站时保持选中复选框
【发布时间】:2022-01-25 18:55:49
【问题描述】:

我使用复选框来切换使用 HTML、CSS 和 JS 的黑色和深色主题颜色。我的导航栏中有这段代码。它运作良好。但是一旦刷新或更改到网站内的其他页面,它就不再保持黑暗。

<div>
  <input type="checkbox" class="checkbox" id="chk" />
  <label class="label" for="chk">
    <i class="fas fa-moon"></i>
    <i class="fas fa-sun"></i>
    <div class="ball"></div>
   </label>
</div>

有人提出了使用本地存储的概念,我尝试了这个,但它不起作用。

const chk = document.getElementById('chk');

chk.addEventListener('change', () => {
    document.body.classList.toggle('dark');
});


// for checkbox remained checked

document.getElementById('chk')(function(){
    var test = localStorage.input === 'true'? true: false;
    document.getElementById('chk')('input').prop('checked', test || false);
});

document.getElementById('chk')('input').on('change', function() {
    localStorage.input = document.getElementById('chk')(this).is(':checked');
    console.log(document.getElementById('chk')(this).is(':checked'));
});

请有人帮助我。

PS:我不是网络开发人员。我在这里和那里为我的博客使用 HTML 和 CSS。我正在使用 GitHub 页面来托管我的网站。 https://amatya-aditya.github.io/

【问题讨论】:

    标签: javascript html checkbox local-storage


    【解决方案1】:

    JavaScript 代码的语法存在一些问题。检查下面的更新代码。

    注意:document.getElementById() 不返回函数

    const chk = document.getElementById('chk');
    
    chk.addEventListener('change', (e) => {
        localStorage.setItem('dark-mode', e.target.checked);
        if ( e.target.checked )
          document.body.classList.add('dark');
        else
          document.body.classList.remove('dark');
        
    });
    
    window.addEventListener('load', () => {
        let value = localStorage.getItem('dark-mode');
        document.getElementById('chk').checked = value === 'true' ? true : false;
        if ( value === 'true' )
          document.body.classList.add('dark');
        else
          document.body.classList.remove('dark');
    })
    

    【讨论】:

    • 感谢哈利勒的努力。我添加了您更正的代码,但它仍然无法正常工作。你可以在这里查看。 amatya-aditya.github.io
    • @AdityaAmatya 我已经更新了代码,你现在可以查看
    • 非常感谢,哈利勒。它现在正在工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多