gpt4 book ai didi

javascript - 使用 jquery cookie 插件设置主体类

转载 作者:行者123 更新时间:2023-11-28 13:44:57 25 4
gpt4 key购买 nike

我正在尝试使用 jQuery Cookie plugin 创建一个“高对比度”样式切换器

我已经绞尽脑汁几个小时了,在 stackoverflow.com 上阅读了很多问题,但我没有解决我的问题。

想法是当单击 ID 为“switch”的 span 元素时,在 body 标记上切换类“highcontrast”。在 CSS 样式表内,我有一组规则,如果 body 标记具有“highcontrast”类,我想应用这些规则。

这是上述场景的 jQuery 代码:

$("#switch").click(function () {
$.cookie('bodyclass', 'highcontrast', { expires: 7, path: '/' });
$('body').toggleClass('highcontrast');
});

如果单击切换元素主体类,则会切换。现在,如果您转到另一个页面,cookie 就在那里并且值已设置,但主体类“highcontrast”不再存在。

我错过了什么?

最佳答案

好的,这已经过验证并且正在运行...

HTML:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Style Switcher</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="../../plugins/cookie/jquery.cookie.js"></script>
<script src="switch.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>

<span id="switch">Switch</span>

</body>
</html>

jQuery:

    $(document).ready(function(){
// Check (onLoad) if the cookie is there and set the class if it is
if ($.cookie('highcontrast') == "yes") {
$("body").addClass("highcontrast");
}

// When the span is clicked
$("#switch").click(function () {
// Check the current cookie value
// If the cookie is empty or set to no, then add highcontrast
if ($.cookie('highcontrast') == "undefined" || $.cookie('highcontrast') == "no") {
// Set cookie value to yes
$.cookie('highcontrast','yes', {expires: 7, path: '/'});
// Add the class to the body
$("body").addClass("highcontrast");
}
// If the cookie was already set to yes then remove it
else {
$.cookie('highcontrast','no', {expires: 7, path: '/'});
$("body").removeClass("highcontrast");
}
});
});

CSS:

    body {
width:100%;
height:100%;
}
body.highcontrast {
background-color:#000;
color:#fff;
}

关于javascript - 使用 jquery cookie 插件设置主体类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15066265/

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