【问题标题】:Adding a darkmode stylesheet to localStorage with jQuery使用 jQuery 向 localStorage 添加暗模式样式表
【发布时间】:2021-02-10 13:08:28
【问题描述】:

所以,我马上就知道,为暗模式使用单独的样式表已经是一种奇怪的方式,但这是我的情况:

我有一个输入触发器,当 .prop("checked", true) 时,将 darkmode.css 切换到 styles.css 上,当 .prop("checked", false) 时,将其删除,您只需标准的“灯光模式”样式。

我想要实现的是,如果主页上有 .prop("checked", true),然后我点击另一个页面,例如“关于我们”,我想保持那个 .prop("checked" , true) 并保持暗模式。

<input type="checkbox" id="darkmodeToggle" class="darkmode"></input>

$("#darkmodeToggle").click(function() {
  if ($("#darkmodeToggle").prop("checked", true)) {
    $("<link>").attr({'rel': 'stylesheet', 'href': 'styles/darkmode.css'}).appendTo('body');
  } else if ($("#darkmodeToggle").prop("checked", false)) {
    $("<link>").attr({'rel': 'stylesheet', 'href': 'styles/styles.css'}).appendTo('body');
    $("<link>").attr({'rel': 'stylesheet', 'href': 'styles/about.styles.css'}).appendTo('body');
    $("<link>").attr({'rel': 'stylesheet', 'href': 'styles/operations.styles.css'}).appendTo('body');
  }});

【问题讨论】:

  • 可以通过替换href来切换!!不附加它!

标签: html jquery hyperlink stylesheet attr


【解决方案1】:

一个好方法是使用localStorage 来获取和设置项目。然后,您可以检查该值在其基本用法中是否为真/假。

jQuery 没有什么真正需要的。 此外,使用prop("checked", true) 设置值。即使它在if 声明中。 因此,您需要做的就是通过prop("checked") 获取布尔值,这将返回以太假或真。

或者在 jQuery 1.6 之前类似: .attr('checked','checked')

<label>Dark mode?
  <input type="checkbox" id="darkmodeToggle" class="darkmode"/>
</label>

var darkModeToggle = $("#darkmodeToggle");

$(function($) {
    if(!localStorage.getItem('darkmode')) {
    console.log('Setting darkmode on first visit')
        localStorage.setItem('darkmode', false)
  }
})

darkModeToggle.click(function() {
  
  if (darkModeToggle.prop("checked")) {
    localStorage.setItem('darkmode', true);
    
    $("<link>").attr({'rel': 'stylesheet', 'href': 'styles/darkmode.css'}).appendTo('body');
  } else if (!darkModeToggle.prop("checked")) {
    localStorage.setItem('darkmode', false);
    
    $("<link>").attr({'rel': 'stylesheet', 'href': 'styles/styles.css'}).appendTo('body');
    $("<link>").attr({'rel': 'stylesheet', 'href': 'styles/about.styles.css'}).appendTo('body');
    $("<link>").attr({'rel': 'stylesheet', 'href': 'styles/operations.styles.css'}).appendTo('body');
  }
  });


【讨论】:

    猜你喜欢
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2022-12-11
    • 2015-08-05
    • 2011-12-02
    • 1970-01-01
    相关资源
    最近更新 更多