亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在瀏覽器首選項中存儲 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 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號