我有一个按钮想要添加功能。当您单击该按钮时,网站的样式将更改为高对比度版本(即样式表 high_contrast.css 被附加到头部)。显然我做错了一些事情,因为下面的代码只是切换当前页面的样式,当您导航到另一个页面时,它会切换回默认样式。我可能不应该每次都设置该变量 highContrast 。我想使用查询 cookie 插件 (https://github.com/carhartl/jquery-cookie) 来完成此任务,但不太明白在这种情况下如何使用它。
这是 HTML
<div id="contrast-btn"><a href="#" rel="css/high-contrast.css">high contrast</a></div>
这是脚本
$(document).ready(function(){
var highContrast = false;
$("#contrast-btn a").click(function () {
if (!(highContrast)) {
$('head').append('<link rel="stylesheet" href="css/high-contrast.css" type="text/css" id="hc_stylesheet"/>');
highContrast = true;
}
else {
// remove the high-contrast style
$("#hc_stylesheet").remove();
highContrast = false;
}
});
});
感谢您的帮助
最佳答案
您必须通过 cookie 获取和设置值:
$(document).ready(function(){
// DRY wrapper function
function appendStyleSheet() {
$('head').append('<link rel="stylesheet" href="css/high-contrast.css" type="text/css" id="hc_stylesheet"/>');
}
// append the style sheet on load if the cookie is set to true
if ($.cookie('high_contrast') == 'true') {
appendStyleSheet();
}
$("#contrast-btn a").click(function () {
if ($.cookie('high_contrast') != 'true') {
appendStyleSheet();
$.cookie('high_contrast', 'true'); // set the cookie to true
}
else {
// remove the high-contrast style
$("#hc_stylesheet").remove();
$.cookie('high_contrast', 'false');
}
});
});
您可以向 cookie 添加过期或站点范围内的有效性等选项,因此如果您希望 cookie 有效期为一年,请将其添加到 cookie 命令中
$.cookie('high_contrast', 'false', {expires: 365});
如果您希望它在整个域中有效(这很可能是您的实现的情况),您可以添加路径“/”:
$.cookie('high_contrast', 'false', {path: '/'});
关于jquery - 为jquery样式切换添加cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11396426/