添加Cookie以切换侧栏 [英] Add cookies to toggle sidebar

查看:52
本文介绍了添加Cookie以切换侧栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的侧边有一个切换的侧栏,现在我想使用cookie使其记住其当前状态.以前已经提到过很多,但是我一直找不到能够与我的代码一起使用的解决方案.(或者也许是,但是我真的很陌生,我可能用错了.)

I have a toggling sidebar on my side, and now I want to use cookies to make it remember what state it's at. This has been brought up a lot before, but I haven't been able to find a solution that works with my code. (Or maybe it does, but I'm really new at this, I could just have used it wrong.)

var main = function() {
    $('.icon-menu').click(function() {
        $('.menu').animate({
            left: "0px"
        }, 200);

        $('body').animate({
            left: "240px"
        }, 200);
    });

    $('.icon-close').click(function() {
        $('.menu').animate({
            left: "-240px"
        }, 200);

        $('body').animate({
            left: "0px"
        }, 200);

    });
};

我调查了此问题,就是我要寻找的东西,但是代码如此不同,以至于我无法正常工作.与在此处输入链接描述 Viktor在这里有用的设置-会更容易用更标准"的东西重做代码?还是可以为菜单和主体设置if命令?

I looked into this ask, it seems to be what I'm looking for, but the codes where so different I didn't get it to work. Same with enter link description here Viktor's helpful setup here - would it be easier to just redo the code with something more "standard"? Or can I set up an if command for both the menu and the body?

感谢所有提示.干杯!

推荐答案

下载并包含 js-cookie,并按如下所示使用它:

Download and include js-cookie, and use it as follows:

$(document).ready(function() {
    $('.icon-menu').click(function() {
        $('.menu').animate({
            left: "0px"
        }, 200);

        $('body').animate({
            left: "240px"
        }, 200);

        Cookies.set('menu-state', 'open');
    });

    $('.icon-close').click(function() {
        $('.menu').animate({
            left: "-240px"
        }, 200);

        $('body').animate({
            left: "0px"
        }, 200);

        Cookies.set('menu-state', 'closed');
    });

    // Open menu (without animation) if it was open last time
    if (Cookies.get('menu-state') === 'open') {
        $('.menu').css({
            left: "0px"
        });

        $('body').css({
            left: "240px"
        });
    } else {
        $('.menu').css({
            left: "-240px"
        });

        $('body').css({
            left: "0px"
        });
    };
});

这篇关于添加Cookie以切换侧栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆