使用localStorage切换具有持久性的CSS样式表

Using localStorage for switching CSS style sheets with persistence

本文关键字:CSS 样式 持久性 localStorage 使用      更新时间:2023-09-26

我遇到一个问题,当在两个单独的样式表(一个蓝色和一个深色)之间切换时,我试图使用localStorage方法来存储用户偏好。

我就是无法让它正常工作,而且我似乎无法调用存储功能,更不用说设置它了

这是javascript和html代码。

<head>
<title>Welcome Page</title>
<link id= "pagestyle" rel="stylesheet" type="text/css" href="blue.css" title= "blue"/>
  <link id= "pagestyle" rel="stylesheet" type="text/css" href="../blue.css" title= "blue" />

<link href='http://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet' type='text/css'>
<script type= "text/javascript">
    function swapstylesheet(sheet) {
        document.getElementById('pagestyle').setAttribute('href',sheet);
    }

    function storebackground(swapstylesheet) {
        localStorage.setItem(swapstylesheet);
    }
    function loadbackground(args) {
        document.getElementById("pagestyle").innerHTML = localStorage.swapstylesheet;
        //code
    }
</script>
<div id ="cssbutton">
    <button id= "blueb"  value = "bluev" class ="css1" onclick = "swapstylesheet('blue.css')">Blue</button>
    <button id= "darkb" value = "darkv" class ="css2" onclick = "swapstylesheet('dark.css')">Dark</button>

有人能告诉我我做错了什么吗?

您没有显示从哪里调用loadbackground,但您的localStorage代码需要如下所示:

 function storebackground(swapstylesheet) {
    localStorage.setItem('sheetKey', swapstylesheet); //you need to give a key and value
 }
 function loadbackground(args) {
    document.getElementById("pagestyle").innerHTML = localStorage.getItem('sheetKey'); //get value by key
    //or document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('sheetKey'));
}

不要切换样式表。创建一个样式表,并为主体提供一个类。这可以通过减少或粗鲁来做得更好。

body.blue { background-color: #006; }
body.dark { background-color: #000; } 
body.blue a { color: #fff; }
body.dark a { color: #600; } 

然后将所有特定的更改作为子样式。将类存储在cookie或存储中,加载页面时检查它是否存在,并将类添加到正文中。