gpt4 book ai didi

带有 cookie 的 jQuery 样式切换器

转载 作者:行者123 更新时间:2023-11-28 12:09:10 25 4
gpt4 key购买 nike

我没有太多的 JavaScript 经验,但我正在学习 jQuery 并一路学习。我的页面上有一个样式表切换器(或主题切换器),但它会在刷新/访问不同页面时切换到默认样式表。

我知道 cookie 用于此,但不知道如何将其实现到我的代码中...

<link rel="stylesheet" type="text/css" href="css/light-theme.css"> (in my head tag, html)

jQuery:
$('#dark').click(function (){
$('link[href="css/light-theme.css"]').attr('href','css/dark-theme.css');
});
$('#light').click(function (){
$('link[href="css/dark-theme.css"]').attr('href','css/light-theme.css');
});

谢谢大家的帮助。

最佳答案

我相信你可以用 cookie 做到这一点,但我会用 HTML5 本地存储来试试

jQuery:

$('#dark').click(function (){
$('link[href="css/light-theme.css"]').attr('href','css/dark-theme.css');
localStorage.stylesheet = 'css/dark-theme.css';
});
$('#light').click(function (){
$('link[href="css/dark-theme.css"]').attr('href','css/light-theme.css');
localStorage.stylesheet = 'css/light-theme.css';
});

不确定您是否必须等待文档准备好才能访问样式表。

$(document).ready(function(){
if(localStorage.stylesheet !== null){
//check which stylesheet is active
if($('link[href="css/dark-theme.css"]').length>0){
$('link[href="css/dark-theme.css"]').attr('href',localStorage.stylesheet);
}else if($('link[href="css/light-theme.css"]').length>0){
$('link[href="css/dark-theme.css"]').attr('href',localStorage.stylesheet);
}

}
})

不过,您将拥有更好的浏览器与 cookie 的兼容性。浏览器可能不支持 localStorage。

if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}

关于带有 cookie 的 jQuery 样式切换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35446169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com