为了账号安全,请及时绑定邮箱和手机立即绑定

如何在浏览器首选项中存储 CSS 类?

如何在浏览器首选项中存储 CSS 类?

九州编程 2023-07-29 13:41:03
(HTML、CSS、脚本,按顺序)<center><a href="FBLINK" class="fa fa-facebook"></a><a href="TWITTERLINK" class="fa fa-twitter"></a><button class="button" onclick="myFunction()">&#9680;</button></center><style>.dark-mode {  background-color: #262626;  color: #d9d9d9;}.dark-mode a, .dark-mode span, .dark-mode h2 a, .dark-mode h1, .dark-mode h2, .dark-mode h3, .dark-mode h4, .dark-mode h5, .dark-mode h6, .dark-mode .post-box-title, .dark-mode strong.tag-heading {  color: #d9d9d9;}.dark-mode div#sidebar h2 span {  background-color: #262626;  border-color: #e5e5e5;}.dark-mode #sidebar .widget {  border-color: #e5e5e5;}.dark-mode .post-entry, .dark-mode .entry-meta {  border-bottom: 1px solid rgba(229,229,229,0.2);}.dark-mode div#blog-pager {  color: #d9d9d9;  background-color: #323232;}</style><script>function myFunction() {   var element = document.body;   element.classList.toggle("dark-mode");}</script>问题是,我想将这些暗模式设置存储在用户浏览器上。已经尝试过sessionStorageand localStorage,但不确定我是否在正确的位置使用了代码,并使用了正确的键/值组合(我有:键是&ldquo;style&rdquo;或&ldquo;class&rdquo;,值是&ldquo;dark-mode&rdquo;) 。是在这些<script>标签之间吗?是在正确的 JavaScript 标签之间吗?是在那段代码里吗?现在,我们将其用作localStorage主要设置。希望我说得足够清楚,感谢您的帮助!
查看完整描述

1 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

您可以随意命名本地存储键,但请记住对值进行相应的操作。


<button onclick="toggleMode()">Toggle theme</button>


<script>

// Theme mode key name

const LS_THEME_KEY = "theme_mode";

// Possible theme mode local storage values

const THEME_MODE_LIGHT = 0;

const THEME_MODE_DARK = 1;

// Class to be applied when dark mode is active

const BODY_DARK_MODE_CLASS = "dark-mode";

// Default theme

const DEFAULT_THEME_MODE = THEME_MODE_DARK;


// Look up current theme mode and modify the body

// tag class list accordingly.

const syncBodyClassList = (setValue) => {

  const currThemeMode = setValue !== undefined ? setValue : parseInt(localStorage.getItem(LS_THEME_KEY) || DEFAULT_THEME_MODE);

  if (currThemeMode === THEME_MODE_DARK) {

    // turn the dark theme on

    document.body.classList.add(BODY_DARK_MODE_CLASS);

  } else {

    // turn the dark theme off

    document.body.classList.remove(BODY_DARK_MODE_CLASS);

  }

};


const setThemeMode = (mode) => {

  localStorage.setItem(LS_THEME_KEY, mode);

  syncBodyClassList(mode);

}


// Toggle current theme and save it into the local storage

function toggleMode() {

  const currentValue = parseInt(localStorage.getItem(LS_THEME_KEY) || DEFAULT_THEME_MODE);

  if (currentValue === THEME_MODE_DARK) {

    setThemeMode(THEME_MODE_LIGHT);

  } else {

    setThemeMode(THEME_MODE_DARK);

  }

}


const initPage = () => {

  syncBodyClassList();

}


initPage();

</script>


查看完整回答
反对 回复 2023-07-29
  • 1 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信