【问题标题】:Cookie to remember css stylesheet preference用于记住 css 样式表首选项的 Cookie
【发布时间】:2020-11-04 12:16:46
【问题描述】:

我需要制作一个 cookie,它会记住 css 样式表首选项。

我将样式表切换为:

function swapStylesheet(sheet){

    document.getElementById('pagestyle').setAttribute('href', sheet);

}

然后从按钮调用它:

<a button class="Button" onclick="swapStylesheet('DayStyle.css')">Light</a>
        
<a button class="Button" onclick="swapStylesheet('NightStyle.css')">Dark</a>

因此它将 href 更改为选择的 css 文件,但在刷新时它会更改回默认值。 有什么方法可以创建一个 cookie 来记住 href 首选项? 它可以适用于所有网站吗?

【问题讨论】:

标签: javascript html css


【解决方案1】:

您可以使用浏览器的 localStorage,因为 cookie 的使用主要用于读取服务器端数据(但如果您真的愿意,您仍然可以使用 cookie)。

显然您也可以使用 sessionStorage,尽管在关闭选项卡/浏览器后首选主题将不可用,因为顾名思义,会话关闭时不会保留 sessionStorage。这会破坏记住用户偏好的目的..

使用 localStorage 的方法:

当用户选择样式时,您可以:

function swapStylesheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
    localStorage.setItem('stylesheet', sheet);
}

在最初加载页面时,您可以使用&lt;body onLoad ="checkLS()"&gt; 函数来检查是否设置了localStorage 并应用样式:

function checkLS () {
    let sheet = localStorage.getItem('stylesheet');
    if (sheet) {
        swapStylesheet(sheet){
    };
}

这样,即使浏览器在两次访问之间关闭,用户首选的样式表/主题也会自动设置..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2018-07-08
    • 1970-01-01
    相关资源
    最近更新 更多