如何保存我的自定义宽度到一个cookie

How can I save my custom width to a cookie?

本文关键字:一个 cookie 自定义 何保存 保存 我的      更新时间:2023-09-26

我正在做一个宽度改变器。我使用jQuery,但我有一个问题。当用户点击按钮时,宽度会立即改变。我想把用户的选择保存在一个cookie中,但是我不知道怎么做。

当前jQuery代码:

$(function()
{
  $(".width-changer").on("click", function(e)
  {
    $(".wrapper").toggleClass("custom-width");
  });
});

我使用这个插件的cookie:

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.3.1/jquery.cookie.js"></script>

在my index.html中。

包装类是我的全局宽度

这是我在i.m explorer &对于chrome浏览器,我认为你应该启用cookies:

$(function()
{
    if ($.cookie('custom_width')=='true') { //add true to this condition
        $(".wrapper").addClass("custom-width");
    };
  $(".width-changer").on("click", function(e)
  {
    $(".wrapper").toggleClass("custom-width");
    if($(".wrapper").hasClass("custom-width"))
        $.cookie('custom_width', 'true');
    else
        $.cookie('custom_width', 'false');
  });
});

我想这是相同的:

https://github.com/carhartl/jquery-cookie

both Method testing:

$(".width-changer").on("click", function (e) {
    var control = $(".wrapper");
    control.toggleClass("custom-width");
    if (control.hasClass("custom-width")) {
        $.cookie('WidthOption', 'custom-width');
    }
    else {
        $.cookie('WidthOption', '');
    }
});

 $(".width-changer").on("click", function (e) {
        var control = $(".wrapper");
        control.toggleClass("custom-width");
        $.cookie('WidthOption', control.width());
    });

获取cookie值:

    $.cookie('WidthOption');

可以使用本地存储localStorage