【问题标题】:jQuery Cookie hide/show divjQuery Cookie 隐藏/显示 div
【发布时间】:2023-03-13 05:05:02
【问题描述】:

我正在尝试使用jQuery Cookie 设置 cookie,以便为新访问者显示警报,当您单击“关闭”按钮时,它将设置 cookie 并阻止显示警报 div。我也想让 cookie 在 24 小时后过期。

我已经尝试了一些代码并让它工作,但是,我现在拥有它的方式,默认情况下会显示警报 div,并且只有在单击关闭后才会隐藏。这很好,但是当 cookie 存在时,警报会在隐藏之前显示片刻。

我将如何修改以下代码,以便我可以默认隐藏 div,如果 cookie 不存在,它将显示,但如果他们点击关闭按钮,它将生成一个 cookie 并隐藏警报24小时?

if ($.cookie('alert')) $('.alert-box').hide();
else {
    $(".close").click(function() {
        $( ".alert-box" ).slideUp( "slow", function() { });
        $.cookie('alert', true);
    });
}

【问题讨论】:

  • 使用CSS默认隐藏元素。

标签: javascript jquery html css cookies


【解决方案1】:

您可以使用 CSS 默认隐藏警报框,并在没有 cookie 时使用 JavaScript 显示它:

CSS:

.alert-box {
    display: none;
}

JavaScript:

// if no cookie
if (!$.cookie('alert')) {
    $( ".alert-box" ).show();
    $(".close").click(function() {
        $( ".alert-box" ).slideUp( "slow" );
        // set the cookie for 24 hours
        var date = new Date();
        date.setTime(date.getTime() + 24 * 60 * 60 * 1000); 
        $.cookie('alert', true, { expires: date });
    });
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多