Save current stylesheet to local storage

只谈情不闲聊 提交于 2020-07-22 09:11:22

问题


I know that this question has been asked, but none of the posts have helped me to get through it.

So, here is the thing - I have two stylesheets on my site. I want to save lately used stylesheet to local storage.

Switching between stylesheets works perfectly.

Here is my code:

    window.onload = function() {
        var currentStylesheet = localStorage.getItem("stylesheet");
        document.getElementById("stylesheet").value = currentStylesheet;
        document.getElementById("stylesheet").setAttribute("href", currentStylesheet);
        }

I got this code from here, and tried to adapt to my use, but sadly - it didn't work. I mean - it does something, but looks like it messes up with stylesheet and it doesn't work at all.


回答1:


You are just forgetting about Storage.setItem(). You stated the you want to 'save' the most recent stylesheet that was used.

I think you are confusing the idea of state here. In your code sample, you read value a from localStorage, but you did not attempt to set localStorage at any point.

Let's look at a minimal example. I prepared a live demo below:

LIVE DEMO

Imagine you have these files:

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link id="active-stylesheet" href="" rel="stylesheet" type="text/css"/>
</head>

<body>
    <div class="switch-buttons">
        <button class="switch-buttons__light button" data-stylesheet="light.css">Go Light</button>
        <button class="switch-buttons__dark button" data-stylesheet="dark.css">Go Dark</button>
    </div>
    <h1>Light and Dark Stylesheets with Web Storage API</h1>
    <h2> See <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage">MDN Storage - Web Storage API</a>.</h2>
    <p>
      Click a button above. The style you select will be 'remembered' when you refresh this page. To reset this demo, click the 'Clear Storage' button.</p>
    <p>
        Faucibus interdum posuere lorem ipsum dolor sit amet, consectetur adipiscing elit duis tristique sollicitudin nibh sit amet commodo nulla facilisi? In metus vulputate eu scelerisque felis imperdiet proin fermentum leo.</p>
    <p>
        Etiam sit amet nisl purus, in mollis nunc sed id semper risus in! Ultricies lacus sed turpis tincidunt id aliquet risus feugiat in ante metus, dictum at tempor commodo, ullamcorper?</p>
    <button id="clear-storage">Clear Storage</button>
    <script src="script.js"></script>
</body>

</html>

light.css

body {
  background-color: #fff0bc;
}

h1, h2, p {
  color: #363636;
}

dark.css

body {
  background-color: #363636;
}

h1, h2, p {
  color: #fff0bc;
}

script.js

var buttons = document.getElementsByClassName("button");
var activeSheet = document.getElementById("active-stylesheet");
var clearStorageButton = document.getElementById("clear-storage");

// Test to see if localStorage already has a value stored
if (localStorage.getItem("lastActiveSheet")) {
     activeSheet.setAttribute("href", localStorage.getItem("lastActiveSheet"));
}

// Assign the event lister to each button
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", switchStyle);  
}

// Create a button to clear localStorage
clearStorageButton.addEventListener("click", clearStorage);

// Set the #active-stylesheet to be the light or dark stylesheet
function switchStyle() {
   var selectedSheet = this.getAttribute("data-stylesheet");
   activeSheet.setAttribute("href", selectedSheet);
   localStorage.setItem("lastActiveSheet", selectedSheet);
}

// Wrapper function to localStorage.clear
function clearStorage() {
  localStorage.clear();
}

If you want your app to remember the most recently used stylesheet, you need to store it into localStorage as a value you can use when the user visits your app again in the future.

As @Hynek had pointed out, it is not a good idea to use window.onLoad. So, in this example, I attached event listeners to all buttons used instead.

In this example, the page has two options to select from: a light and a dark theme for contrast. If the user selects a theme, it will be remembered the next time the page is refreshed.

The key here is the state. You want your app to have 'memory'. So, you need to add the functionality to write, read, and clear the memory. I suggest reading more through MDN - Storage - Web APIs to see how you can implement this. On MDN, there are even more examples too!



来源:https://stackoverflow.com/questions/52920019/save-current-stylesheet-to-local-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!