带有cookie的jQuery样式切换器
我在JavaScript方面没有太多经验,但我正在进入jQuery并学习。我的页面上有一个样式表切换器(或主题切换器),但在刷新/访问其他页面时,它会切换到默认样式表 我知道cookies用于此,但不知道如何在我的代码中实现它带有cookie的jQuery样式切换器,jquery,css,Jquery,Css,我在JavaScript方面没有太多经验,但我正在进入jQuery并学习。我的页面上有一个样式表切换器(或主题切换器),但在刷新/访问其他页面时,它会切换到默认样式表 我知道cookies用于此,但不知道如何在我的代码中实现它 <link rel="stylesheet" type="text/css" href="css/light-theme.css"> (in my head tag, html) jQuery: $('#dark').click(function (){
<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');
});
(在我的头标签中,html)
jQuery:
$('#暗')。单击(函数(){
$('link[href=“css/light-theme.css”]”)attr('href','css/dark-theme.css');
});
$('#light')。单击(函数(){
$('link[href=“css/dark-theme.css”]”)attr('href','css/light-theme.css');
});
谢谢大家的帮助。我相信你可以用cookies来做,但我会用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);
}
}
})
不过,浏览器与cookies的兼容性会更好。浏览器可能不支持本地存储
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}