[英]CSS Toggle Switch to add a class to a DIV with local storage
我正在嘗試創建一個簡單的撥動開關,以將新的 class 添加到正文標簽。 默認情況下,頁面是紅色的。 通過單擊按鈕,頁面在紅色和藍色之間切換。
這是我到目前為止的代碼 - 然后切換顏色按鈕會將主體 class 標記更改為藍色
<body>
<p>Click the button to change the colour of page</p>
<button onclick="myFunction()">Change background colour</button>
<script>
function myFunction() {
var element = document.body;
element.classList.toggle("blue");
}
</script>
</body>
CSS 位
body {
background-color: red;
color: white;
}
body.blue {
background-color: blue;
}
我正在努力解決的問題是在刷新頁面或移動到另一個頁面時保留設置。 有沒有辦法通過本地存儲和 javascript 來存儲它?
在此先感謝,布賴恩
對於更動態的解決方案(如果您有兩個以上的 colors 會發生什么?),我會改為 go 和 CSS 變量,其中默認顏色為紅色。 Stack Overflow 不允許從 localStorage 中讀取數據,因此我將注釋掉該代碼,而是使用一個變量來進行演示。
我確實認為代碼是不言自明的。
const BACKGROUND_KEY = 'background'; var forDemoPurposeOnly = ''; function myFunction() { let isBlue = readFromLocalStorage(BACKGROUND_KEY) == 'blue'; let color = (isBlue)? 'red': 'blue'; setBackgroundColor(color); } function setBackgroundColor(color) { let root = document.documentElement; root.style.setProperty('--user-selected-background', color); setInLocalStorage(BACKGROUND_KEY, color); } function readFromLocalStorage(key) { return forDemoPurposeOnly; // return localStorage.getItem(key); } function setInLocalStorage(key, value) { forDemoPurposeOnly = value; // localStorage.setItem(key, value); }
:root { --background-color: var(--user-selected-background, red); /* defaults to 'red' */ } body { background-color: var(--background-color); }
<body onload="setBackgroundColor(readFromLocalStorage('background'))"> <p>Click the button to change the colour of page</p> <button onclick="myFunction()">Change background colour</button> </body>
本地存儲 API 使用起來超級簡單。 localStorage
在瀏覽器中可作為全局變量使用,您可以使用鍵存儲字符串值,然后使用鍵檢索值。
function myFunction() {
var element = document.body;
element.classList.toggle("blue");
var background = localStorage.getItem('background')
if (background === 'blue') {
localStorage.setItem('background', 'red')
} else {
localStorage.setItem('background', 'blue')
}
}
(function() {
var background = localStorage.getItem('background')
if (background === 'blue') {
document.body.classList.add(background)
}
})()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.