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

(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主要设置。


希望我说得足够清楚,感谢您的帮助!


九州编程
浏览 86回答 1
1回答

翻阅古今

您可以随意命名本地存储键,但请记住对值进行相应的操作。<button onclick="toggleMode()">Toggle theme</button><script>// Theme mode key nameconst LS_THEME_KEY = "theme_mode";// Possible theme mode local storage valuesconst THEME_MODE_LIGHT = 0;const THEME_MODE_DARK = 1;// Class to be applied when dark mode is activeconst BODY_DARK_MODE_CLASS = "dark-mode";// Default themeconst DEFAULT_THEME_MODE = THEME_MODE_DARK;// Look up current theme mode and modify the body// tag class list accordingly.const syncBodyClassList = (setValue) => {&nbsp; const currThemeMode = setValue !== undefined ? setValue : parseInt(localStorage.getItem(LS_THEME_KEY) || DEFAULT_THEME_MODE);&nbsp; if (currThemeMode === THEME_MODE_DARK) {&nbsp; &nbsp; // turn the dark theme on&nbsp; &nbsp; document.body.classList.add(BODY_DARK_MODE_CLASS);&nbsp; } else {&nbsp; &nbsp; // turn the dark theme off&nbsp; &nbsp; document.body.classList.remove(BODY_DARK_MODE_CLASS);&nbsp; }};const setThemeMode = (mode) => {&nbsp; localStorage.setItem(LS_THEME_KEY, mode);&nbsp; syncBodyClassList(mode);}// Toggle current theme and save it into the local storagefunction toggleMode() {&nbsp; const currentValue = parseInt(localStorage.getItem(LS_THEME_KEY) || DEFAULT_THEME_MODE);&nbsp; if (currentValue === THEME_MODE_DARK) {&nbsp; &nbsp; setThemeMode(THEME_MODE_LIGHT);&nbsp; } else {&nbsp; &nbsp; setThemeMode(THEME_MODE_DARK);&nbsp; }}const initPage = () => {&nbsp; syncBodyClassList();}initPage();</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript