我有一个想要添加功能的按钮。当你点击按钮时,网站的样式会变成一个高对比度的版本(例如,样式表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;
}
});
});谢谢你的帮忙
发布于 2012-07-09 21:58:54
您必须通过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: '/'});发布于 2012-07-09 21:57:02
您可以在全局上下文中设置highContrast,这将帮助您稍后在同一页面上进行评估
var highContrast = false;
$(document).ready(function(){
// [...]
highContrast = true;
// [...]
});但是每次页面刷新时,该值都会丢失,因此您可以使用jquery-cookie设置cookie
$.cookie('highContrast', 'true', { path: '/' });并在页面加载时阅读:
if($.cookie('highContrast') && $.cookie('highContrast') === "true") {};通过设置path = '/',cookie将在整个域中可用。
因此,您的代码将更改为:
$(document).ready(function(){
// Append the stylesheet on page load
if ($.cookie('highContrast') === "true") {
$('head').append('<link rel="stylesheet" href="css/high-contrast.css" type="text/css" id="hc_stylesheet"/>');
}
// Add the click handler to switch the stylesheet on and off
$("#contrast-btn a").click(function () {
if (!($.cookie('highContrast') === "true")) {
$('head').append('<link rel="stylesheet" href="css/high-contrast.css" type="text/css" id="hc_stylesheet"/>');
$.cookie('highContrast','true',{path:'/'});
}
else {
// remove the high-contrast style
$("#hc_stylesheet").remove();
$.cookie('highContrast','false',{path:'/'});
}
});
});https://stackoverflow.com/questions/11396426
复制相似问题