如何让用户保存自定义样式表设置

How to let a user save custom stylesheet settings

本文关键字:样式 设置 自定义 保存 用户      更新时间:2023-09-26

我有一些样式表,但我如何让用户保存自定义样式表从上次他们在网站上?我可以在Jquery和html5 ?

有很多不同的方法可以做到这一点,但如果你不想让你的服务器与过多的数据库/cookie阻塞(假设你没有后台认证系统),那么你可以保存一个类,所以…比如,你需要做CSS:

    $(document).ready(function () {
        applyTheme();
    });

    $(".theme").click(function (e) {
        e.preventDefault();
        //removes current stylesheet
        $("#customSheet").remove();
        //gets the theme name the user clicked
        var themeName = $(this)[0].id;
        //sets it to storage
        setTheme(themeName);
        //appends to the head so it loads
        $('head').append('<link href="css/' + themeName + '.css" rel="stylesheet" id="customSheet" />');
    });
    // sets local storage, pretty self explanatory, localstorage is an object that persists across the browser state until the user clears it out, usually because of some other plugin or just clears the cache
    function setTheme(theme) {
        localStorage.setItem('themeClass', theme);
    }
    //how to apply the theme to the document's body so that it can conditionally load 
    function applyTheme() {
        var theme = localStorage.getItem('themeClass');
        if (theme) {
            $('head').append('<link rel="stylesheet" type="text/css" href="css/' + theme + '.css" id="customSheet">');
        }
    }

如果你喜欢的CSS文件名为theme1,它会加载theme1如果你把它放在正确的路径

编辑:

完成这种特定方式的HTML是

<div id="theme">
    <input type="button" id="theme1" class="theme">
    <input type="button" id="theme2" class="theme">
</div>

这将与所有回到IE8没有问题....http://caniuse.com/搜索= localstorage

你可以把它复制粘贴到某个地方,它会和你当前的东西一起工作

编辑:对于那些想知道整个代码库之后会是什么样子的人来说:http://pastebin.ca/3212318

是的,你可以这样做。您可以使用cookie、数据库或浏览器存储。如果你使用浏览器存储,它将是HTML5,如果你知道你的JavaScript,这是相当简单的完成。否则,你有一个简单的方法,那就是使用cookie,如果你有一个身份验证系统,将该cookie与注销时删除的cookie分开,因此这些设置将保留,直到用户删除他们的cookie。

cookie,例如来自MSDN

document.cookie = "test1=Hello";
document.cookie = "test2=World";
var cookieValue = document.cookie.replace(/(?:(?:^|.*;'s*)test2's*'='s*([^;]*).*$)|^.*$/, "$1");
function alertCookieValue() {
  alert(cookieValue);
}

document.cookie = myStyle;

在这里看到一个完整的例子我如何从cookie中创建和读取值?

然后,更可取的路线,HTML5,一个例子是在这里本地存储- HTML5演示代码

编辑:

这里有一个粘贴文件夹,可能会为你做(看到你在正确的方向,从我来自哪里)。http://pastebin.ca/3211127