使用localStorage以持久性方式切换CSS样式表 [英] Using localStorage for switching CSS style sheets with persistence

查看:114
本文介绍了使用localStorage以持久性方式切换CSS样式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,我在尝试使用localStorage方法在两个单独的样式表(一个蓝色和一个黑色)之间切换时存储用户首选项。

I am having an issue wherein I am trying to use the localStorage method to store user preferences when switching between two separate style sheets, one blue and one dark.

我只是无法让它运行,我似乎无法调用存储功能,更不用说设置它了。

I just can't get it to function, and I seem to be unable to call the storage function let alone set it.

这是javascript和html代码。

Here is the javascript and html code.

<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>

任何人都能告诉我我的意思我做错了吗?

Anyone can tell me what I am doing wrong?

推荐答案

你没有显示你在哪里打电话 loadbackground from但你的localStorage代码必须如下所示:

You didn't show where you're calling loadbackground from but your localStorage code needs to be like below:

 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'));
}

这篇关于使用localStorage以持久性方式切换CSS样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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