将当前样式表保存到本地存储 [英] Save current stylesheet to local storage

查看:29
本文介绍了将当前样式表保存到本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有人问过这个问题,但没有一个帖子帮助我解决这个问题.

所以,事情就是这样 - 我的网站上有两个样式表.我想将最近使用的样式表保存到本地存储.

在样式表之间切换非常有效.

这是我的代码:

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

我从这里获得此代码,并试图适应我的使用,但遗憾的是 - 它没有用.我的意思是 - 它做了某事,但看起来它与样式表混乱并且根本不起作用.

解决方案

你只是忘记了 Storage.setItem().您声明要保存"最近使用的样式表.

我认为您在这里混淆了状态的概念.在您的代码示例中,您从 localStorage 读取值 a,但您没有尝试在任何时候设置 localStorage.

让我们看一个最小的例子.我在下面准备了一个现场演示:

现场演示

假设您有这些文件:

index.html

<头><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"/><身体><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>

<h1>带有 Web Storage API 的浅色和深色样式表</h1><h2>请参阅 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage">MDN 存储 - Web 存储 API</a>.</h2><p>单击上方的按钮.当您刷新此页面时,您选择的样式将被记住".要重置此演示,请单击清除存储"按钮.</p><p>Faucibus interdum posuere lorem ipsum dolor sat amet, consectetur adipiscing elit duis tristique sollicitudin nibh sat amet commodo nulla facilisi?在 metus vulputate eu scelerisque felis imperdiet proinfermentum leo 中.<p>Etiam 坐在 amet nisl purus,在 mollis nunc sed id semper risus!Ultricies lacus sed turpis tincidunt id aliquet risus feugiat in ante metus, 格言 at tempor commodo, ullamcorper?</p><button id="clear-storage">清除存储</button><script src="script.js"></script></html>

light.css

body {背景颜色:#fff0bc;}h1, h2, p {颜色:#363636;}

dark.css

body {背景颜色:#363636;}h1, h2, p {颜色:#fff0bc;}

script.js

var buttons = document.getElementsByClassName("button");var activeSheet = document.getElementById("active-stylesheet");var clearStorageButton = document.getElementById("clear-storage");//测试 localStorage 是否已经存储了一个值如果(localStorage.getItem(lastActiveSheet")){activeSheet.setAttribute("href", localStorage.getItem("lastActiveSheet"));}//为每个按钮分配事件列表for (var i = 0; i 

如果您希望您的应用记住最近使用的样式表,您需要将它存储到 localStorage 中作为一个值,您可以在将来用户再次访问您的应用时使用该值.

正如@Hynek 所指出的,使用 window.onLoad 不是一个好主意.因此,在此示例中,我将事件侦听器附加到所有使用的按钮上.

在此示例中,页面有两个选项可供选择:用于对比的明暗主题.如果用户选择了一个主题,下次刷新页面时会记住它.

这里的关键是状态.您希望您的应用程序具有内存".因此,您需要添加写入读取清除内存的功能.我建议通过 MDN - Storage - Web APIs 阅读更多内容以看看你如何实现这一点.在 MDN 上,还有更多示例!

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.

解决方案

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!

这篇关于将当前样式表保存到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆