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

标签 javascript jquery cookies

我正在尝试使用 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/

相关文章:

javascript - 当窗口大小更改时,将根 div 中心保持在页面上

javascript - 尝试使用 ngx-cookie 获取 cookie,但如果我 F5 页面,则为 'document is not defined'

javascript - 运行 javascript 一次

javascript - 使用与 API 交互的表单提交问题

javascript - 不使用 jquery animate() 动画元素

javascript - 带有 Json 对象的 React-stockcharts

php - 将动态文本框传递给 jquery

javascript - 如何在WordPress中使用上传特色图片的URL

javascript - 使用 python 抓取 dechtech 网站

Javascript:添加 CSS 类并保存到 cookie